I need to return an array in php and use it in javascript. When I print the returned value it prints empty string. How do I make mistake?
$.ajax({
type: "POST",
url: "sort2.php",
success: function(result){
alert(result[0]);
}
});
//sort2.php
$data[0] = "book";
$data[1] = "pen";
$data[2] = "school";
echo json_encode($data);
You have to parse the JSON data
$.ajax({
type: "POST",
url: "sort2.php",
success: function(result){
//Parse Json to Array
result = jQuery.parseJSON(result);
alert(result) // would output the result array
}
});
You can change the dataType
of your $.ajax()
request to json
and have jQuery automatically decode your JSON object from string.
Alternatively, you could add to your PHP header('Content-Type: application/json')
and jQuery should also automatically decode your JSON string.
In your sort2.php
file, change the following code:
echo json_encode($data);
to
header('Content-Type: application/json');
echo json_encode($data);
What it does is tell the client browser to treat the response as JSON data and parse accordingly and not as HTML, which is the default.
Also, make sure sort2.php
file is in the same folder as the html file from where you are making the ajax call.
Hope this helps.
you also can use the $.post method by jQuery, which would look like this: (so you don't need to change your php script, see here: jQuery Post).
$.post(
'sort2.php', //script you request
{}, //post-data you want to send
function(result) {
alert(result[0]); /*i like more: console.log(result); this way you can see it in firebug e.g.) */
},
'json' //data-type you expect
);