Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force fail for $.ajax (deferred)object from php

Tags:

jquery

ajax

i am doing a little ajax ping pong and was wondering if it is possible to force a deferred ajax object to fall into fail state from PHP.

$.ajax({
    url: 'example.com/post',
    dataType: 'json'
})
.done(function(data) {
    console.log(data);
})
.fail(function(data) {
    console.log(data);
});

and in php

function post() {
if (false) {
    echo json_encode(array('all good'));
} else {
    ???
}
}
like image 504
Nick Avatar asked May 29 '12 14:05

Nick


1 Answers

You can return an error header:

header('HTTP/1.0 404 Not found');
exit;

This will cause jQuery to run its error handler and in turn fail the Ajax deferred. Basically status codes like 4xx and 5xx` will do the trick.

like image 188
Ja͢ck Avatar answered Nov 17 '22 09:11

Ja͢ck