Skip to content Skip to sidebar Skip to footer

When Should I Return True/false To AJAX And When Should I Echo "true"/"false"

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.

Solution 1:

You 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:

  1. HTML (if it's going to populate page elements)

  2. JSON (if you want a lightweight, fast way to send data to the client)

  3. XML (if you want a heavier-weight, fast way to send data to the client)

  4. 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.


Solution 2:

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');
    }
});

Solution 3:

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"


Solution 4:

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") {…}
} …

Post a Comment for "When Should I Return True/false To AJAX And When Should I Echo "true"/"false""