Passing a PHP Array through AJAX

If you are creating dynamic elements on your page, you will need to be able to send information to and from the browser. There’s lots of documentation on how to POST data using AJAX to the server side. What if you want to return an array of data back to the browser?

$.ajax({
    url: "<?php echo site_url('test/urlGoesHere/'); ?>",
    type: 'POST',
    data: form_data,
    dataType:"json",
    success: function(data) {
        alert(data[0]);
   }

Marking the dataType as json here is key.

In your PHP file, use json_encode to send your array:

print json_encode($my_array);

If you don’t want to save the array into a variable, you can also just write the array between the json_encode parantheses:

print json_encode(array("name"=>$name,"title"=>"Ms."));

Then in your AJAX success, you can access the array elements this way:

data.name[0]; //the first name element
data.title;  // "Ms."
data[0];

If this was your array: array("Jack", "Mr."), then your AJAX data can be handled like this:

$.ajax({
    url: "",
    type: 'POST',
    data: form_data,
    dataType:"json",
    success: function(data) {
        var name = data[0];
        var title = data[1];
        alert('Name: ' + name + ', Title: ' + title);
   }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s