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

匆匆过客 提交于 2019-12-13 05:52:52

问题


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.

I thought about something around the cookies? But I'm still wondering what is the cause of it. Please guys, help on this.

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>

Please give me only PURE, RAW JAVASCRIPT solutions, no jQuery.


回答1:


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.



来源:https://stackoverflow.com/questions/37953199/ajax-request-doesnt-work-the-first-time-but-works-thereafter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!