theflarenet
theflarenet

Reputation: 656

AJAX Error Handling from PHP

My current script only handles errors with a vague & general error message when the execution fails but I'd like to have it return various error messages. Many of the other answers I find are similar to what I already have where I'm unable to do what I desire here.

Current AJAX (What I require changed):

$.ajax(
{
    url: './ajax.php',
    data: {value1: 'test', value2: 'test', isChecked: isChecked},
    dataType: 'json',
    success: this.exeSuccess,
    error: this.exeError
});


this.exeSuccess = function(){
    var currentRow = $(this).closest('tr');
    // Highlights table row to denote successful execution
    currentRow.toggleClass('colorcode');
};

this.exeError = function(){
    alert("Error. Please try again.");
    return false;
};

Current PHP:

if (isset($_GET['value1']) && isset($_GET['value2']) && isset($_GET['isChecked'])) {

    // Execution logic here... if it fails, the whole script terminates
    echo json_encode("");
}

What I plan on doing with PHP to return detailed error messages to AJAX:

if (isset($_GET['value1']) && isset($_GET['value1']) && isset($_GET['isChecked'])) {

    $errorMessage = "";

    if (isset($_GET['isChecked']) == 'false'){
        $errorMessage = "The check box is false";
    } else {
        $errorMessage = "The check box is true";
    }

    echo json_encode("$errorMessage");  // But how I handle it in the AJAX error:?
}

How could I get the error messages handled in "AJAX error:" so that different alert([error_message]) can be executed?

Upvotes: 0

Views: 131

Answers (1)

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10093

The error callback for jQuery's ajax method accepts three arguments which you can use to get more info about the error:

 Function( jqXHR jqXHR, String textStatus, String errorThrown )

Please note that error callback will only be called if there is some error while getting response from the server e.g. server can't be reached or some server error occurred while trying to generate a response for your ajax request.

If your php file is able to send back a response, it's usually handled by success callback because in effect the ajax succeeded and returned a proper response.

If you still want to handle your custom error cases in error callback, you should also add http error codes in your ajax response headers.

Upvotes: 1

Related Questions