jQuery AJAX从PHP返回

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'); }
});

SUBMIT_FORM.PHP

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.

If you want to execute error command in jquery you can try using: throw new Exception("Invalid"); inside your php code (where error should invoke).

This will cause http server to return error code 500 to your javascript code.

YOur concept is wrong. error condtion means error in ajax call Change your code to this

$.ajax({
type: "POST",
url: 'submit_form.php',
data: dataString,
error: function() {
 alert('Error'); //here the error is the error in ajax call.eg failing to call or a 404..etc
 },
success: function(msg) {
if(msg=='error'){
   alert('Error'); //this is the error you are looking for
}else{
 alert('Success'); 
}

}
});

Your PHP

if ( count of rows in db < x  )
 {
echo 'error'; //this is  enough
exit;

}

i think you are little confused about jquery error setting, according to jquery

error : A function to be called if the request fails.

so your error code will be fired only because of the following reasons

404 Error – ajax file not found error

500 Error – ajax internal system error

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);
}