JavaScript

AJAX request with JavaScript (no jQuery, no libs)

February 5, 2022

AJAX request with JavaScript (no jQuery, no libs)

In this article you will learn how to make an AJAX request with JavaScript, without using any library, such as jQuery, or a framework.

AJAX request with JavaScript cover

What’s up programmer, how are you? Today we are going to learn more about JavaScript and AJAX!

In the early days, AJAX with JavaScript was done via XMLHttpRequest, but it was a bit laborious

Then, with the arrival of jQuery, it became easier and more convenient to do, but we depended on an external lib

And then an internal API was created, called Fetch, which we can create requests with pure JavaScript in a much easier way than XMLHttpRequest

And it is with the Fetch resource that we will make our AJAX request for this article

Let’s see a practical example:

const URL = 'https://dog.ceo/api/breeds/list/all'
 fetch(`${URL}`)
 .then((body) => body.json())
 .then((data) => {
  console.log(data)
 })
.catch((error) => console.error('Error:', error.message || error))

First we define the API URL, this is an API about dogs and it is open, you can use the example

And if there was any parameter in the URL, we could wrap it in variables too

Then the fetch method works on the basis of Promises, which will continue the code as the response is received

If you receive the data from the API, in the console we will have the data of the dogs printed

If not, we will receive the error that occurred in this process to debug and readjust the request

Check out the return:

We received all dog breeds as expected for this API route

Compatibility

Remembering that this feature is ‘new’, so it may not work with some browsers

See the compatibility list

Conclusion

In this article we learned how to make an AJAX request with JavaScript

Without using any library, like jQuery

In this process we use Fetch, which is the most modern alternative available at the moment and has the Promises feature

Want to learn more about JS? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x