Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) jQuery and AJAX Posting Data with jQuery

Daniel Fitzhugh
Daniel Fitzhugh
9,715 Points

How to Post Data using Regular Javascript

FYI those who want to know how to post data (as shown in this video) but with regular javascript....

I personally don't like learning stuff in jQuery without knowing how to do it regular javascript.... so I read a couple of articles (this one was particularly useful: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript) and worked it out.

Any problems with this code? As you can see, it's ridiculously long compared to the jQuery version:

const form = document.querySelector("form");

form.addEventListener("submit", function (event) {

    // TAKE BACK DEFAULT BEHAVIOURS FROM THE HTML FORM

    event.preventDefault();
    const url = form.getAttribute("action");

    // GATHER UP FORM DATA INTO A SINGLE QUERY STRING

    const formElements = document.querySelectorAll("form input, form textarea, form select");
    const arrayForString = [];

    for ( let i = 0; i < formElements.length; i += 1 ) {
        if ( formElements[i].hasAttribute("name") ) {
            const element = formElements[i];
            const name = element.getAttribute("name");
            const value = element.value;
            const nameValue = encodeURIComponent(name) + "=" + encodeURIComponent(value);
            arrayForString.push(nameValue);
        }
    }

    const formData = arrayForString.join("&");

    // CREATE THE XHR REQUEST

    const xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if ( xhr.readyState === 4 && xhr.status === 200 ) {
            document.querySelector("#signup").innerHTML = "<p>Thanks for signing up!</p>";
        }
    }

    xhr.open("POST", url);

    xhr.send(formData);

});
Masha Blair
Masha Blair
13,005 Points

Thank you so much for preparing this, Daniel!

fantastic you!

3 Answers

Steven Parker
Steven Parker
229,644 Points

And now you know why jQuery is so popular for using AJAX. :wink:

Another advantage is that the jQuery methods resolve certain CORS security access issues that would take even more code (or the use of a CORS proxy) to handle.

Nour El-din El-helw
Nour El-din El-helw
8,241 Points

So, I tried to do the same thing but using the fetch api..

document.querySelector('form').addEventListener('submit', e => {
      e.preventDefault();

      const formElements = document.querySelectorAll('input[type=text]', 'input[type=email]');

      let encodedFormElements = [];

      for( let i =0; i < formElements; i++ ) {
        encodedFormElements.push(
          encodeURIComponent(formElements[i].getAttribute('name')) + '=' +  
          encodeURIComponent(formElements[i].value));
      }

      let encodedData = encodedFormElements.join('&');

      const data = {
        method: 'POST', 
        body: encodedData
      }

      fetch(this.action, data)
        .then(() => {
          document.querySelector('#signup').innerHTML = '<p>Thanks for signing up!</p>';
        })
    })

but for some reason when I try to console.log(encodedData) it logs white space

Steven Parker
Steven Parker
229,644 Points

I haven't tried this out but one thing you might consider is that while "fetch" provides a greatly simplified interface, it also does not resolve CORS issues the way jQuery does.

Nour El-din El-helw
Nour El-din El-helw
8,241 Points

Yeah, everything has it's pros and cons. I just did so because at the end of the fetch api workshop,Guil told us to remake all our projects that use xhrhttpobject and jQuery for ajax with fetch api, and to be honest it's kind of fun too. xD

Jake Goldstein
Jake Goldstein
1,304 Points

Thanks man I bookmarked this because I agree I like to at least see how things are done in vanilla javascript when learning frameworks or new libraries