Reputation: 36766
I have the following PHP code that returns a JSON object via Ajax to the client.
function loadAll(){
$knowledgeHandler = new KnowledgeLevelHandler();
$json = $knowledgeHandler->loadAll();
header('Content-type: application/json');
print $json;
}
I have a test function assigned to the success callback of jQuery Ajax.
successCallback = function(data){
alert("A");
}
options = {
"data": data,
"async": false,
"type": "post",
"success":successCallback
}
$.ajax(url, options);
When I remove the header('Content-type: text/json');
from PHP code, the callback is executed, but when it is executed, the success callback isn't executed. What is wrong?
Upvotes: 0
Views: 213
Reputation: 2633
I believe you need to specify the returned data type as JSON in your JQuery AJAX call.
http://api.jquery.com/jQuery.ajax/
The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data.
successCallback = function(data){
alert("A");
}
options = {
data: data,
async: false,
type: "POST",
success: "successCallback",
dataType: "json"
}
$.ajax(url, options);
Your successCallback function will now contain a data object, through which you can access your variables; data.var_1, data.some_other_var, etc.
Neal
Upvotes: 2
Reputation: 1148
Try this:
options = {
"data": data,
"async": false,
"type": "post",
"success":successCallback,
"dataType: "json"
}
$.ajax(url, options);
Upvotes: 1
Reputation: 747
Try telling jQuery you're expecting json back.
options = {
"data": data,
"async": false,
"type": "post",
"success":successCallback,
"dataType": "json"
}
you could also add a error callback with xhr, msg, code as the args and output those to get a better idea of what is wrong.
Upvotes: 1