Search code examples
javascriptajaxxmlhttprequestforms

Result from XMLHttpRequest request disappears


Problem:

When I click the submit button in my HTML form it calls an JavaScript function with an Ajax request. - This return successfully, but the result disappears almost instantly.

I am just wondering if I am missing something here (other than jquery, which I know is an easier way, but xmlhttprequest is a current requirement)

I have pasted my code below - maybe I am missing a little mistake (I hope) it has been a while since I focused on Ajax.

HTML Code:

<body>

   <form>
       <label>Name:</label>
       <input type="text" id="name" value="test1" placeholder="Your name" >

       <label>Email:</label>
       <input type="email" id="email" value="[email protected]" placeholder="Your email" >

       <label>Country:</label>
       <input type="text" id="country" value="test3" placeholder="Your country" >

       <input type="submit" value="Submit Form" onclick="postRequest()" >
   </form>
   <div id="repsonse"></div>
    <script src="scripts.js"></script>
</body>

JavaScript:

function postRequest()
{
   //data from the form
   var name = document.getElementById('name').value;
   var email = document.getElementById('email').value;
   var country = document.getElementById('country').value;
   var submitForm = "submitForm";

   //ajax objects
   var http = new XMLHttpRequest();
   var url = "functions_ajax.php";
   var params = JSON.stringify({ callFunction : submitForm, name : name, email : email, country : country });

   //alert(params);

   //Deal with ajax components
   http.open("POST", url, true);
   http.setRequestHeader("Content-type", "application/json; charset=utf-8");
   http.send(params);

   http.onreadystatechange = function() {

    //alert("Checking Status "+http.status+" "+http.readyState);

    if(http.readyState == 4 && http.status == 200) {
        //Return the data from the ajax request
        console.log(http.responseText);
        document.getElementById("repsonse").innerHTML = "<h1>Success!</h1>";
    }
    else
    {
       console.log(http.responseText);
       console.log(http.status);
       document.getElementById("repsonse").innerHTML = "<h1>No Cigar! HTTP Status == "+http.status+" </h1>";
    }
} 
}

Solution

  • When you click the button, which is a submit button, you submit the form, causing the page to refresh.

    The quickest solution is to change the input to:

    <input type="button" ... />
    

    As this will prevent the form submission.

    Or, you can get the event object in your handler. You should set your event handler up through JS by giving your button an ID (say, "myButton"), and hooking up the handler like so:

    document.getElementById("myButton").onclick = function(e) {
        // ... body of your function here
        // or, call postRequest() here
        e.preventDefault();
    }
    

    Then, you'd remove the onclick attribute from the button, as the function is being bound to the click event through javascript.

    That'll prevent the form from being submitted.

    Alternatively, you can hook an onsubmit handler to your form. Give your form an id, such as "myForm", and use:

    document.getElementById("myForm").onsubmit = function(e) {
        e.preventDefault();
    }
    

    You could also call postRequest() from the form's onsubmit handler, but in that case you'd want to keep the submit button and not turn it into a normal button.

    Make sure that when you're setting these event handlers, though, you're doing it in a script at the bottom of the page, or in a function that runs during or after the window's onload event.