Ajax表单提交错误

I am using the code below to send an email via ajax. The problem is that even if the email is not sent e.g i localhost or when there is no internet connection, the success command will still be returned by the script. Kindly advise me on what modifications I should make to the code for it to detect whenever an error is encountered.

$('#send_button').click(function(e) {
     $("#sending").removeClass("hidden_div");//just to know that we have some data

     alerts = '';
     if($("input[name=names]").val() == ''){
        alerts += "1";
        $("#error_name").removeClass("hidden_div");
     }

     if(alerts != ''){
        $("#sending").addClass("hidden_div");
     } else {
         $.ajax({
                url:'index.php',
                type:'POST',
                data:$("#form").serialize(),
                cache: false,
                success: function(data){ 
                    show_ok();
                },
                error: function(){
                    $("#msg_not_sent").removeClass("hidden_div");
                    $( "#msg_not_sent" ).empty().append( "An error has occurred. Kindly try again." );
                  }
        });     }
    e.preventDefault();
});

I believe this happens if the code you are calling doesn't error in the way jQuery expects, or you aren't using a matching return data type you can get this. There's a way around it though.

complete: function (data) {
    if (data.status == "200") {
    }

data should contain a success property.

Since your call will most likely will succeed, you need to also take into account the result of the action.

PHP:

$success = false;
if(somethingOk){
    $success = true;
}
echo json_encode(array(
    'success' => $success
));

JS:

dataType: 'json',        // make sure you get a json
success: function(data){ 
    if (data.success){
        show_ok();
    } else {
        alert("error");
    }
},