For this kind of situation I like to use an object I return as JSON so it's a bit more flexible:
$resultObj = new stdClass ();
$resultObj->success = true;
$resultObj->msg = '';
//your code here
//in case of SQL error
$resultObj->success = false;
$resultObj->msg = 'There was an error while processing your requests';
//return the response
$echo json_encode($resultObj);
And then in your jQuery request you can set the dataType property to json so that it will turn the response into an object in case of HTTP success so you can handle the error in the success function:
$.ajax({
url : 'yourpage.php',
success : function(data, status, xhr) {
if (data.success === true) {
alert('Everything ok');
} else {
alert('An error occurred: ' + data.msg);
}
},
error : function(xhr, status, ex) {
alert('An error occurred during the communication with the server: ' + xhr.status +' - ' + xhr.statusText);
},
dataType : 'json'
});
As others have said you can have your PHP script return a HTTP 404 error so that instead your error is redirected to the javascript error handler, but I like to keep that error handler for unhandled errors like an untrapped exception or an HTTP failure, and for the errors that I handled on the server side I also handle them on the client-side inside the success function.
Hope this helps.