0

I'm working on a connection module in ajax/php using jquery. I need to throw an exception from php to ajax, to indicate whether email or password is false.

I searched all over the web for a way to use the 'error' function proposed by jquery's ajax. Found some solutions, none of them works.

Tried throwing a php exception : error function is not catching it ; tried avoiding using error function by sending json encoded data : no way of using it in success function... Error function seems to only catch server errors, which is really NOT interesting.

Can anybody, please, help me find a way to communicate errors from php through ajax ?

1
  • what sort of error do u want Commented Oct 18, 2013 at 9:55

2 Answers 2

4

Set the request statuscode in the php response to 4XX or 5XX. That will make you end up in the error/fail callback.

I dones't necessarily have to be a value in the list. For example, you can create your own:

StatusCode: 550
StatusText: "My Custom Error"

Which, if I recall correctly, would look like this in PHP:

header('HTTP/1.0 550 My Custom Error');

Finally, send the error details to the client to notify them of what went wrong. You can either place the info in the header, or serialize the exception using json_encode()

<?php

try {
    if (some_bad_condition) {
        throw new Exception('Test error', 123);
    }
    echo json_encode(array(
        'result' => 'vanilla!',
    ));
} catch (Exception $e) {
    echo json_encode(array(
        'error' => array(
            'msg' => $e->getMessage(),
            'code' => $e->getCode(),
        ),
    ));
}

?>

Client side:

$.ajax({
    url: 'page.php',
    data: { 'some_bad_condition': true }
}).done(function(data){

    console.log('success!', data);

}).fail(function(jqXhr){

    var errorObject = $.parseJSON(jqXhr.responseText);
    console.log('something went wrong:', errorObject);
    //jqXhr.status === 550
    //jqXhr.statusText === 'My Custom Error'

});

Don't forget to specify the correct mimetype in your PHP file. That way jQuery will know that it's a JSON response without you specifying it explicitly.

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
Sign up to request clarification or add additional context in comments.

2 Comments

@YonnTrimoreau See my update. You could make use of success + error callbacks if you prefer that.
did it 3 times ;) SO seems to have a problem accepting it, please be sure i'll retry until it works ;)
0

Try using this plugin:

AJAXForm

Get it here.

The ajax handles the submission of the form, and if there is an error the error callback will be used.

I think I have previously used this. It is quite easy to use and check also if your return status code is correct in your php.

1 Comment

Thank you, but underestimating other members by sending them easy-to-use plugins and not teach them how to do it by themselves is quite insulting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.