Fetch, jQuery.ajax, and XMLHttpRequest

404-Not-Found
2 min readOct 10, 2020

Today, I want to discuss the differences between these three since I ran across them during one of my studies. All of these are methods of requesting data using Javascript.

XMLHttpRequest

This method is one of the older methods of out of the three and was used prior to Fetch. What it does is, bind callback handlers to a request object which are invoked based on success, failure and on-progress states.

Here’s an example of what such a request would look like:

let request = new XMLHttpRequest()
request.open('GET', 'https://api.myapp.com/users')
request.requestType = 'JSON'
request.onLoad = function(){
console.log(request.response)
}
request.send()

So, why would you need to know and antiquated method of requesting? While most companies are using fetch, some legacy code data base might still have these types of request and you will need to understand its mechanics just incase you have to work in it.

jQuery.ajax

jQuery.ajax requires that you import the jQuery library first and the way you write the syntax is a bit different.

Example of what an AJAX request looks like:

function(){
$.ajax({
url: 'https://api.myapp.com/users',
data: null,
type: 'GET',
success: function(response){console.log(JSON.stringify(response))} })
}

This is a bit simpler and again would only be used in the event that you needed to work with legacy code. You’ll notice we have to use $.ajax where the $ is a reference to jQuery object.

Fetch

Finally, the last one we will go over is fetch, which is what everyone is using nowadays because it written for modern Javascript. Another thing to know about Fetch is that it uses Promises rather than callbacks.

Let’s look at an example of what this would look like compared to the others:

fetch('https://api.myapp.com/users')
.then(response => response.json())
.then(json => console.log(json))

This greatly simplifies the lines of code and achieves pretty much the same thing as the other two! You’ll probably be using this the most, but again the other two are good to know.

--

--

404-Not-Found
0 Followers

I enjoy long naps on the couch, deep conversations about video games, and romantic dinners with anime.