I have some non-uniformity as to how my client-side jQuery handles my JSON ajax responses via server-side PHP.
Here are two example ajax calls I have:
function checkOrders() {
$.ajax({
type: "POST" ,
url:"/service/index.php" ,
data: {
q: "checkOrders"
} ,
complete: function(result) {
// note here the JSON.parse() clause
var x = JSON.parse(result.responseText);
if (x['unhandled_status']>0) {
noty({
text: '<center>There are currently <b>'+x['unhandled_status']+'</b> unhandled Orders.',
type: "information",
layout: "topRight",
modal: false ,
timeout: 5000
}
});
}
} ,
xhrFields: {
withCredentials: true
}
});
}
Note in the above example I have to JSON.parse()
the responseText
from my PHP page in order to deal with it as an object. It somehow sees the overall PHP response as an object, and I have to pull the responseText
from that object and JSON.parse()
it, in order to use it.
Now here is another ajax call that I have, whereby the returned response, I can use directly as a json response - meaning, somehow the PHP page does not return a full "object" but ONLY returns the json and my ajax call somehow already knows it is JSON and I do not need to JSON.parse()
it:
function getUnfiledOrders() {
$.ajax({
type: "POST" ,
url:"/service/index.php" ,
data: {
queryType: "getUnfiledOrders"
} ,
success: function(result) {
if (result['total_records'] >0) {
noty({
text: result['response'],
type: "error",
modal: false,
dismissQueue: true,
layout: "topRight",
theme: 'defaultTheme'
});
}
} ,
xhrFields: {
withCredentials: true
}
});
}
In this case, I do not need to JSON.parse() the responseText
in order to treat the response as a JSON object.
Both PHP response scripts look something like this:
header('content-type:application/json');
$array = array("total_records"=>3,"response"=>"SUCCESS");
echo json_encode($array);
Can anybody clue me in on this non-uniformity?
EDIT:
I realized that I had two different callbacks in each of the above ajax calls. One was on complete
and the other was on success
.
When I switched them both to success
the returned response from my ajax request was handled uniformly.
So I guess my question now is:
- Why is there a non-uniformity between these two callbacks?
- Which is better to use?