Somehow I have confused myself.
Somehow I got it in my head that when hitting PHP with AJAX (like $.post), you had to echo back a "true" or "false" instead of returning true/false. I see now that is not the case, but can someone break it down for me?
Is it that there is a problem testing a boolean? Like here
...
$.post('ajax/doThing',{data: data},
function(response) {
if(response) {
doThis();
}else{
doThat();
}
That is the problem case, correct? Here I cannot return true/false, instead I must echo back a string and test the string, yes?
if(response === "true")
But I have seen boolean true/falses returned to ajax functions. What is the use of this, if you cannot test a boolean on the AJAX side? And why can't ajax test a boolean?
Or am I still confused?
EDIT
Just wanted to thank everyone for their good answers on this. I am now +2 smrter.
Somehow I have confused myself.
Somehow I got it in my head that when hitting PHP with AJAX (like $.post), you had to echo back a "true" or "false" instead of returning true/false. I see now that is not the case, but can someone break it down for me?
Is it that there is a problem testing a boolean? Like here
...
$.post('ajax/doThing',{data: data},
function(response) {
if(response) {
doThis();
}else{
doThat();
}
That is the problem case, correct? Here I cannot return true/false, instead I must echo back a string and test the string, yes?
if(response === "true")
But I have seen boolean true/falses returned to ajax functions. What is the use of this, if you cannot test a boolean on the AJAX side? And why can't ajax test a boolean?
Or am I still confused?
EDIT
Just wanted to thank everyone for their good answers on this. I am now +2 smrter.
Share Improve this question edited Feb 5, 2013 at 13:34 K.K. Smith asked Feb 5, 2013 at 13:06 K.K. SmithK.K. Smith 9922 gold badges10 silver badges28 bronze badges 04 Answers
Reset to default 6You might also look at returning HTTP error codes rather than returning a "success" response (HTTP status code 200) when the request wasn't really successful, and then use an error
callback to handle unsuccessful requests.
But if you want to keep using status code 200 (and a lot of people do that):
The data transferred between the client and the server is always text. The trick is to make sure that the client and server agree on how the client should deserialize the text (transform it upon receipt). Typically you might return one of four things:
HTML (if it's going to populate page elements)
JSON (if you want a lightweight, fast way to send data to the client)
XML (if you want a heavier-weight, fast way to send data to the client)
Plain text (for whatever you want, really)
What the client does will depend on what Content-Type
header you use in your PHP page.
My guess is that you're using any of several content types that end up passing on the data as a string to your callback. The string "true"
is truthy, but so is the string "false"
(only blank strings are falsey).
Long story short: I'd probably use this in my PHP:
header('Content-Type', 'application/json');
...and the return this text from it:
{"success": true}
or
{"success": false}
...and then in your success handler:
if (response.success) {
// It was true
}
else {
// It was false
}
Alternately, you can return a Content-Type
of text/plain
and use
if (response === "true") {
// It was true
}
else {
// It was false
}
...but that's kind of hand-deserializing where you could get the infrastructure to do it for you.
Your script should either return a response that translates into a JavaScript equivalent of your PHP variables to make such comparisons possible or use HTTP status codes to convey an error condition.
Response handling
jQuery.ajax()
and friends interpret the response (automatically by default) based on the response headers that you send, be it XML, JSON, etc.
The below code outputs a JSON formatted response:
header('Content-Type: application/json');
echo json_encode(array(
'success' => true,
));
The output that is sent to the browser looks like this:
{"success": true}
Inside your success handler you can now use the following code:
if (response.success) { ... }
Error handling
jQuery.ajax()
can also handle HTTP status code responses other than the regular 200 OK
, e.g.:
header('404 Not found');
exit;
This will invoke your error handler:
$.ajax({
url: ...,
error: function(xhr, status, msg) {
// xhr - see http://api.jquery.com/jQuery.ajax/#jqXHR
// status - "error"
// msg - "Not found"
alert('Error code ' + xhr.code + ' encountered');
}
});
Ajax calls expects a text returned by your scripts, when you return a php bool, it will not be outputted, so you need to echo "something", and its does not have to be "true" or "false"
All depends on your server response. If you use appropriate MIME types, jQuery might automatically JSON.parse()
the response for you, passing the boolean true
to your callback. If it does not recognize JSON, it will pass the textual result "true"
which you need to compare against:
// PHP:
header('Content-Type', 'application/json');
echo true; // or "true" or json_encode(true)
// JavaScript (with jQuery.ajax):
… function callback(response) {
typeof response; // "boolean"
if (response) {…}
} …
// PHP:
header('Content-Type', 'text/plain'); // or similar, also implicit
echo "true";
// JavaScript (with jQuery.ajax):
… function callback(response) {
typeof response; // "string"
if (response == "true") {…}
} …