New to using this Jquery AJAX method. So i'm making an AJAX call with Jquery, In my PHP script i'm checking a condition to be true from my Database, before I pass in my datastring and bind the variables, then execute that query. Both the script and Database insert work correctly.
My question is, how can I get it to display the error message in my AJAX call on return from my PHP script?
JS
$.ajax({
type: "POST",
url: 'submit_form.php',
data: dataString,
error: function() { alert('Error'); },
success: function() { alert('Success'); }
});
if ( count of rows in db < x )
{
return false;
exit();
}
if this condition is true I want to stop execution of my script and execute the error condition in my AJAX function.
elseif ($stmt = $mysqli->prepare("INSERT INTO blah (stuff, morestuff) values (?, ?)")) {
/* Bind our params */
$stmt->bind_param("ss", $param1, $param1);
/* Set our params */
$param1= $_POST["name"];
$param2= $_POST["email"];
/* Execute the prepared Statement */
$stmt->execute();
/* Close the statement */
$stmt->close();
}
if the first condition is false then I want to return the success function in my ajax call which it is currently doing.
To invoke the error handler of your $.ajax, you can write the following code in PHP (for FastCGI):
header('Status: 404 Not found');
exit;
Alternatively, use header('HTTP/1.0 404 Not Found') if you're not using FastCGI.
Personally I wouldn't use this approach, because it blurs the line between web server errors and application errors.
You're better off with an error mechanism like:
echo json_encode(array('error' => array(
'message' => 'Error message',
'code' => 123,
)));
exit;
Inside your success handler:
if (data.error) {
alert(data.error.message);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With