How to pass an array of strings from PHP to Javascript using $.ajax()?

ajax, javascript, jquery, php

Solution

<?php // test.php
$myArray = array(1, 2, 3);
echo json_encode($myArray);
?>

HTML File:

$(function() {
    $.getJSON('http://localhost/test.php', function(data) {
        $(data).each(function(key, value) {
            // Will alert 1, 2 and 3
            alert(value);
        });
    });
});

Problem

I have a PHP script that retrieves names (strings) from database. I would like to pass this array to Javascript using $.ajax(). I cannot understand how should I encode the array in PHP and then decode it in Javascript. Could someone give an example code for this ? Thanks a lot !!

Original source