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 OKstatus 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:
* Except for this exception.