Fun “duh” Mentals— AJAX

Brad Hankee
Code a la Carte
Published in
2 min readOct 17, 2017

Fun as in “Fun”, Duh as in “I knew that”, Mental as in “I will remember this!”

AJAX: (Asynchronous JavaScript and XML) is what we use to send requests to the server and allows responses from that server to be handled via JavaScript.

Asynchronous: Means that a request to the server will not hold up the page or app, the user can still use the site while the request is being processed.

JavaScript: Obvious, come on!

XML: Extensible Markup Language — A way to structure using customizable tags so that the data is organized in an efficient manner. We now mostly use JSON since it is JavaScript.

The main point to focus on as a developer is to know that there is a call back function attached that runs if and when the response successfully comes back.

note: If you send out multiple requests there is no way to know the order of how they will be returned. So it is possible that the second request will return before the first. This is a result of being asynchronous.

GET vs POST

To simplify the two you would use GET when you want to retrieve info from the server, such as search results. On the other hand if you were sending information to the server to be stored in a database you would use POST. One major aspect of GET is that it will add the criteria to the end of the URL which can lead to security concerns if say a password or SSN is being utilized. To contrast POST sends it’s information in the body, not the URL.

Vanilla JavaScript GET Request:

var xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘file.html’);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById(‘myId’).innerHTML = xhr.responseText;
}
};
function sendAJAX() {
xhr.send();
document.getElementById(‘myOtherId’).style.display = ‘none’;
}

The .readyState part means that the request is complete and in this case when this is true would continue the anonymous function. The .responseText is the data being pulled from the “file.html”.

This entire block can also be done via JQuery with a few lines starting with:

$.getJSON(url, function(){})

Of course using Node and Express it’s just as easy but I really enjoy learning what is actually happening under all the abstraction, and it makes me appreciate the libraries and frameworks a little more as well, ok a lot more!

There are books written about AJAX but I wanted to just touch on the basics of the two commonly used parts GET andPOST and write about them to help concrete the ideas in my head so next time I am building a Node and Express App I will have that much more understanding.

Follow me at Twitter.

— Brad

--

--

Brad Hankee
Code a la Carte

Full stack developer / foodie that writes about daily learnings.