Getting jQuery.ajax to interpret the response as an error
I'm struggling to understand how to get jQuery.ajax to interpret a failed MySQL UPDATE query as an error. Here's my code:
jQuery:
$.ajax({
type:'POST',
url:'/ajax/registration.php',
data:{formData: formData},
success:function(data){eformDef.forms.registration.success(data);},
error:function(data){eformDef.forms.registration.success(data);}
});
PHP
$data = $_POST['formData'];
$firstName = mysql_real_escape_string($data['first name']);
$lastName = mysql_real_escape_string($data['last name']);
$email = mysql_real_escape_string($data['email address']);
$password = mysql_real_escape_string($data['password']);
mysql_query("INSERT INTO users (first_name, last_name, email, password) VALUES (开发者_如何转开发'$firstName', '$lastName', '$email', '$password')") or die(mysql_error());
No matter what--even if I make the mysql_query syntax invalid--the ajax call always interprets the response as a success. I assume that's because the mysql_error() gets sent back as the response, the ajax call reads that as a string, and apparently considers that to be a success. Of course I can deal with this by checking the response string in the $.ajax success function, but this seems a bit illogical. In cases where I can test for a data type using the $.ajax dataType option, this isn't an issue. But with an UPDATE query like the one above, I always get a string as a response.
Since there is a workaround (checking the string in the success function), this isn't a critical issue. But if there is a more correct way of doing this, I'd much prefer that.
PHP will send a 200 OK
status no matter what*, so there is no way to jQuery to detect an error.
You have two possibilities:
Have the PHP script explicitly output something like "OK" or an JSON encoded array with a status code. Have the jQuery side explicitly look for that "OK" and throw an error if it's not present.
Have the PHP script throw an error status code if an error occurs, for example:
$query = mysql_query(......); if (!$query) { header("HTTP/1.1 500 Internal Server Error"); echo mysql_error(); // Detailed error message in the response body die(); }
* Except for this exception.
The Ajax call will only interpret the response as an error if the HTTP status code indicates that there was an error. die
does not set the HTTP status code to 500 (at least the PHP documentation doesn't say so). If you throw an exception in your code instead of just using die
, then PHP should return a 500 HTTP status.
精彩评论