ash ash - 5 months ago 13
PHP Question

xmlhttp.readyState returns 2 even though xmlhttp.status equals 200

I'm sending an email through ajax to contact php. Php script sends the email successfully, but ajax xmlhttp.readyState is keep returing 2 even though xmlhttp.status is 200.

params = "name=" + name + "&email=" + email + "&message=" + message + "&telephone=" + telephone;

xmlhttp.open("POST", "contact.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){

if(xmlhttp.responseText == "fill_form"){
note.innerHTML = "Please fill the required fields properly";
return;
}

if(xmlhttp.responseText == "Sent"){
serverMessage.innerHTML = "Thanks. If it is a request or complaint we well get back to you soon";
}
}
else{
serverMessage.innerHTML = "Some internal error occured while sending the email. Please try again later";
$('#myModal').modal('show')
}

submitBtn.innerHTML = "SEND MESSAGE";
submitBtn.disabled = false;
}


Contact.php

<?php

$name=$_POST['name'];
$email=$_POST['email'];
$message=$_POST['message'];
$telephone=$_POST['telephone'];

$mail_to_send_to = "abc@gmail.com";
$feed_back_mail = "name@myDomainName.com";

if (empty($name) || empty($email)|| empty($message))
{
echo "fill_form";
}
else{

$from="From:$feed_back_mail"."\r\n"."Reply-To:$email"."\r\n" ;
$subject="Users feed back Contact";

if(empty($telephone)){
$telephone = "No telephone sent my user";
}

$message = "Telephone: $telephone\r\nSender's Email : $email \r\n \r\n$message \r\n";

$isSent = mail($mail_to_send_to, $subject, $message, $from);

if($isSent){
echo $isSent;
}
else{
echo "not_sent";
}
}


?>

What am doing wrong?

Answer

Remember that your onreadystatechange callback will be called multiple times as the ready state changes. Your current code responds to the first callback expecting it to be done. But it's quite normal for you to get a call before that with readyState 2 ("headers received").

So just wait until you get readyState 4:

xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4){
        // Done, what happened?
        if(xmlhttp.status == 200){
            // All good
        }
        else{
            // Something went wrong
        }
    }
};
Comments