Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an array from an AJAX call?

People also ask

Can we return a value from ajax call?

You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.

How do I return from ajax?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

What is array in ajax?

An Array is used to store multiple values in a single variable. This can be used to pass the group of related values as data to the $. ajax for processing and get the response. E.g. pass all checked checkboxes values, selected values from the list.


Use JSON to transfer data types (arrays and objects) between client and server.

In PHP:

  • json_encode
  • json_decode

In JavaScript:

  • JSON.stringify
  • JSON.parse

PHP:

echo json_encode($id_numbers);

JavaScript:

id_numbers = JSON.parse(msg);

As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.

id_numbers = new Array();
$.ajax({
    url:"Example.php",
    type:"POST",
    success:function(msg){
        id_numbers = msg;
    },
    dataType:"json"
});

Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.


@Xeon06, nice but just as a fyi for those that read this thread and tried like me... when returning the array from php => json_encode($theArray). converts to a string which to me isn't easy to manipulate esp for soft js users like myself.

Inside js, you are trying to get the array values and/or keys of the array u r better off using JSON.parse as in var jsArray = JSON.parse(data) where data is return array from php. the json encoded string is converted to js object that can now be manipulated easily.

e.g. foo={one:1, two:2, three:3} - gotten after JSON.parse

for (key in foo){ console.log("foo["+ key +"]="+ foo[key]) } - prints to ur firebug console. voila!