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 what I have been doing this:
PHP File (Example.php):
<?php
$id_numbers = array('NES-ZL','NES-AL','SNS-ZL');
for ($i=0; $i<count($the_array); $i++){
echo $id_numbers[$i];
echo '|';
}
?>
JS File:
id_numbers = new Array();
$.ajax({
url:"Example.php",
type:"POST",
success:function(msg){
id_numbers = msg.split('|');
}
});
My current method is just a little too convoluted for my taste.
What I'd like to do is to be able to just
return $id_numbers;
on the PHP side and directly translate it to a Javascript array after the AJAX call.
Ideas, anyone?
This question is related to
javascript
php
jquery
json
ajax
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/
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.
@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!
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 :)
Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.
Source: Stackoverflow.com