javascriptajaxxmlhttprequestreadystate

AJAX request doesn't work the first time but works thereafter


I'm making a simple function as it is shown on w3schools official website. I'm trying to run a function of an AJAX request.

I guess it's all working well except the fact that the code ONLY runs after it fails the first time. I mean, let's say you just came the first time to my website and you try to submit the first time, it just refreshes the page and nothing happens.

As far as I'm aware I tried to debug using alert functions in each line to find if the request was really being made. I found that the readyState jumps from 1 to 4 the very first time the code runs (in every browser, different computers), but next time it will render readyState 1, 2, 3 and 4 and BANG it will work and submit.

Javascript function code (inside head tag)

function sendForm() {
        
    var criarRequest = new XMLHttpRequest();
    criarRequest.onreadystatechange = function() {  
        if (criarRequest.readyState == 4 && criarRequest.status == 200) {
            document.getElementById("contacts").innerHTML = criarRequest.responseText;
        } 
    };
    //var loading  = document.getElementById("contacts").innerHTML = "A enviar...";
    var inputEmail = document.getElementById("email").value;
    var inputMensagem = document.getElementById("mensagem").value;  
    criarRequest.open("POST", "sendEmail.php", true);
    criarRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    criarRequest.send("email="+inputEmail+"&mensagem="+inputEmail);
}

HTML code form/inputs

<form>
    <input style="width:220px; height:39px" type="text" id="email" placeholder="Email" /> 
    <br  /> <br  />
    <textarea style="width:220px; height:100px" id="mensagem" placeholder="Mensagem"></textarea>
    <br  /> <br  />
    <button id="enviar" onclick="sendForm()">Enviar</button>
</form>

Solution

  • actually very simple:P your button is default attribute 'type' of "submit" and when that happens, the form gets submitted causing a refresh. Add 'type="button"' to change this functionality and you should not have a refresh anymore allowing the ajax to finish its request.