I\'m searching for a better solution to making an AJAX call with jQuery, having the PHP file return an array, and have it come out client-side as a Javascript array. Here is
Php has a super sexy function for this, just pass the array to it:
$json = json_encode($var);
$.ajax({
url:"Example.php",
type:"POST",
dataType : "json",
success:function(msg){
console.info(msg);
}
});
simples :)
well, I know that I'm a bit too late, but I tried all of your solutions and with no success!
So here is how I managed to do it.
First of all, I'm working on an Asp.Net MVC project.
The Only thing I changed was in my c# method getInvitation
:
public ActionResult getInvitation (Guid s_ID)
{
using (var db = new cRM_Verband_BWEntities())
{
var listSidsMit = (from data in db.TERMINEINLADUNGEN where data.RECID_KOMMUNIKATIONEN == s_ID select data.RECID_MITARBEITER.ToString()).ToArray();
return Json(listSidsMit);
}
}
SuccessFunction in JS :
function successFunction(result) {
console.log(result);
}
I changed the Method Type from string[]
to ActionResult
and of course at the end I wrapped my array listSidsMit
with the Json method.
Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.
Have a look at json_encode
(http://php.net/manual/en/function.json-encode.php). It is available as of PHP 5.2. Use the parameter dataType: 'json'
to have it parsed for you. You'll have the Object as the first argument in success then. For further information have a look at the jQuery-documentation: http://api.jquery.com/jQuery.ajax/
@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!
Use JSON to transfer data types (arrays and objects) between client and server.
In PHP:
In JavaScript:
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"
});