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