Ajax失败,状态为0

时间:2015-03-03 18:56:39

标签: php jquery ajax

我的ajax请求总是失败,状态为0.正在调用的PHP文件正在执行所有代码。我无法找到请求失败的原因。这是ajax代码:

$(document).ready(function() {
// Get the form.
var form = $('#reg-form');

// Get the messages div.
var formMessages = $('#login_form');

// Set up an event listener for the contact form.
$(form).submit(function(event) {
    // Stop the browser from submitting the form.
    //e.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    alert("Data submitted");
    var submitresponse = $.ajax({
        type: 'POST',
        url: "mailer.php",
        data: formData,
        dataType: "json",
        });
            submitresponse.done(function(response) {
            alert("Hi");
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');
            alert(response);    
            // Set the message text.
            $(formMessages).text(response);

            // Clear the form.
            //$('#name').val('');
            //$('#email').val('');
            //$('#Address').val('');
            });
                submitresponse.fail(function(xhr,status,response) {
                alert("Hii");
                console.log(arguments);
                alert(status);  
                // Make sure that the formMessages div has the 'error' class.
                $(formMessages).removeClass('success');
                $(formMessages).addClass('error');

                // Set the message text.
                //if (data.responseText !== '') {
                alert(xhr.responsetext);    
                //  $(formMessages).text(data.responseText);
                //} else {
                    //$(formMessages).text('Oops! An error occured and your message could not be sent.');
                //}
                $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {

// This is the default error handler for ajax request.

// Extract all the information required to understand.
var requestResponse = {
url: ajaxSettings.url,
method: ajaxSettings.type,
data: ajaxSettings.data,
httpStatus: jqXHR.status,
error: thrownError || jqXHR.statusText,
data: ajaxSettings.data
};

console.error(requestResponse)
// Notify the user so he might not wonder.
alert('Something went wrong, Please try again');
});
                });
            });
});

PHP代码如下:

  <?php
  $servername = "*";
  $username = "*";
  $password = "*";
  $dbname = "*";
  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);
  if ($conn->connect_error) {
  //die("Connection failed: " . $conn->connect_error);
  die("Something went wrong. Please try again or contact front desk.           <br/>");
  }
 // Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $address = trim($_POST["Address"]);
    $class = $_POST["class"];
    $school = $_POST["school"];
    $city = $_POST["City"];
    $fname = $_POST["f_name"];
    $mobileno = $_POST["mobileno"];
     // Check that data was sent to the mailer.
    if ( empty($name) OR empty($address) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }
   $sql = "INSERT INTO registrations(Name, Father_Name,Email,Class,School,Address,City,Mobile_No,Reg_time) values ('$name','$fname','$email','$class','$school','$address','$city',$mobileno,now())";
    if (!mysqli_query($conn,$sql))
 {
 die('Error: ' . mysqli_error($conn));
 }
 //echo "Your Information Was Successfully Posted"; 
 mysqli_close($conn);
       // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = $email;

    // Set the email subject.
    $subject = "ISMART Registration";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$address\n";
    $email_content .= "Class: $class\n";

    // Build the email headers.
    $email_headers = "From: ismart@asd.co.in";
    // Send the email.
    if (mail($recipient, $subject, $email_content,$email_headers)) {
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
      echo "Oops! Something went wrong and we couldn't send your message.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

控制台日志显示: 对象{url:“mailer.php”,方法:“POST”,数据:“name = Nitish + Garg&amp; f_name = sdfs&amp; class = 11&amp; school = DAV + P ... + 1-A%2C + PWSSB + House% 2C + Barakuan + Road&amp; City = Patiala“,httpStatus:0,错误:”错误“} 请帮忙!

1 个答案:

答案 0 :(得分:0)

带有0的httpStatus意味着Ajax调用没有从服务器获得完整的响应。某处存在断开连接,您无法从服务器获取任何内容,也不会获得完整响应。我先检查一下超时。