Search code examples
phpjavascriptajaxstatus

Can I return an output status from a JQuery AJAX request with PHP?


I have an AJAX request (using JQuery) that calls a PHP script which does some database business. The request code is as follows:

$.ajax({
    url: "script.php",
    data: { value: value
        },
    type: 'post',
    success: function(output){
        alert(output);
    }
});

However, I wanted to see if there was a way to also (in addition to the unchanged output string) return a status. It can be as simple as an integer. The point is I want to disable a button (with Javascript) if the PHP script for any reason fails to connect to mySQL, but I still want the PHP scripts output exactly as it would be.

I tried the error option:

...
success: function(output){
        alert(output);
    },
error: function(output){
        // do something
    }

but I do not know how to make PHP display an error and continue on the rest of the script. Again, I don't want to tamper at all with the output string.

In pseudo-code, I'm looking for something like this:

$.ajax({
    url: "script.php",
    data: { value: value
        },
    type: 'post',
    success: function(output){
        if(output.status == 0){
            alert(output);
        }else{
            // do something else
        }
    }
});

Is anything of the sort possible? Thanks for any and all help!


Solution

  • I usually return data from the server in JSON format. This way I can return as many different types of data as may be needed by the success function in javascript.

    basically in PHP you would do something like

    $response = new stdClass();
    $response->error = 'Could not connect to Mysql';
    $response->message = 'Some other text';
    echo json_encode($response);
    

    in JQuery, the ajax() method would automatically detect that the response is json and parse it into a javascript object, so you could access like this

    if (typeof response.error !== undefined) alert(response.error);
    

    for more on that look at dataType argument for the ajax() method in the jQuery documentation.