0

Googling how to achieve this is proving difficult as everyone seems determined to get you to use jQuery for every simple task these days. I've made a rich experience on my site and gone to great lengths to avoid unnecessarily using jQuery, and now that I've come to the contact form, I'm slightly stumped.

On a previous website I used jQuery to submit a form without refreshing the page and then get the result and display it in a div under the form. Now I want to achieve the same effect without jQuery. This is the code I used before:

$('#contactform').submit(function(event) {
    event.preventDefault();
    $.ajax({
        type: "POST",
        url: "contact.php",
        data: $(this).serialize(),
        success: function(data){
            $('#result').html(data);
        }
    });
});

Can someone please help me to achieve this in pure JS? This is the last thing on my site that requires JavaScript so I really don't want to have to invoke jQuery now for something so simple as all my effort to code lovely scroll-to-top buttons, retina image replacement, sliders, and drop-down menus without it will all have been in vain...

  • Do you have some code already? Possible duplicate: http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery – kosmos Jun 14 '14 at 10:18
  • I only have the jQuery above. All I could really find searching were tutorials about how to use `preventDefault` which obviously doesn't help. Is this where you would use an event listener? Or instead does the form submit button get an `on click`? The link you posted looks a bit beyond me to be honest, but as far as I can see it doesn't help me with the form side of things (i.e. not refreshing the page and passing the form action to contact.php with JS). – user3740132 Jun 14 '14 at 10:24

1 Answers1

0
document.querySelector('#contactform').submit = function(event) {
    event.preventDefault();
    var xhr = new XMLHttpRequest();
    xhr.open('POST', "contact.php", true);
    xhr.data = this.serialize();
    xhr.onload = function(data){
            document.querySelector('#result').innerHTML = data;
        }
    xhr.send();
};

Haven't tested this but the above should give you an idea of how to do it.

cnvzmxcvmcx
  • 1,061
  • 2
  • 15
  • 32
  • Clicking submit just refreshes the page? Safari thinks it's submitted a form ('Refreshing this page will resend a form') though. – user3740132 Jun 14 '14 at 10:32
  • 1
    You can use `event.preventDefault()` to stop form submitting. But, also, you can use `return false` at the end of instruction to make sure that the form won't be submitted. – kosmos Jun 14 '14 at 10:43
  • As kmsdev pointed out, remove `event.preventDefault()` and add `return false` at the end of function. My answer is just a literal translation, so I should leave it unchanged . Check [this answer](http://stackoverflow.com/a/1357151/1615721) for detailed difference between the two. – cnvzmxcvmcx Jun 14 '14 at 12:04