Return errors from PHP run via. AJAX?

Is there a way to get PHP to return an AJAX error code if the PHP script fails somewhere? I was following a tutorial and typed this in to my PHP:

$return['error'] = true;
$return['msg'] = "Could not connect to DB";

And all was well, until I realised it was JSON data. Is there a way to return errors using standard $_POST and returned HTML data (as in, trigger jQuery's AJAX error: event?


Solution 1:

I don't know about jQuery, but if it distinguishes between successful and unsuccessful (HTTP 200 OK vs. HTTP != 200) Ajax requests, you might want your PHP script respond with an HTTP code not equal to 200:

if ($everything_is_ok)
    {
        header('Content-Type: application/json');
        print json_encode($result);
    }
else
    {
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
    }

Solution 2:

$return = array();
$return['msg'] = "Could not connect to DB";

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest')
{
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');
    die(json_encode($return));
}