Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 !!

like image 498
Misha Moroshko Avatar asked Aug 17 '10 06:08

Misha Moroshko


1 Answers

<?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);
        });
    });
});
like image 137
Matt Williamson Avatar answered Oct 26 '22 06:10

Matt Williamson