DEV Community

Cover image for Using async await with jQuery’s $.ajax

Using async await with jQuery’s $.ajax

Peter Tasker on December 14, 2017

Photo by Denys Nevozhai on Unsplash If you’re like me, you’re probably stuck using jQuery more often than not. It’s everywhere, and to be honest i...
Collapse
 
dschep profile image
Daniel Schep

Good to know that's available, but why not just use fetch?

Collapse
 
ptasker profile image
Peter Tasker

I'm glad some one brought up fetch()! Fetch is pretty sweet, but I've found it to be less than perfect when you need to modify headers, particularly for authentication.

Out of the box jQuery's $.ajax() will forward any headers currently set on the page. Fetch however is a lot lower level, similar to using XHR directly. That being the case headers, cookies and authentication parameters have to be set manually.

If you're using GET or a simple POST then yeah, fetch() is fine. But if you want to do anything more complex jQuery, or an Ajax library can be easier.

See: swizec.com/blog/waste-hours-fetch-...

The big benefit to using jQuery's ajax over Axios or Superagent is that it's probably already in your browsers cache from another website, so it's the most common sense tool to use.

But yeah, I use fetch when I can... 😃

Collapse
 
hrmny profile image
Leah

Or you know, just use fetch + unfetch as a polyfill

Collapse
 
_martinjose28_ profile image
martin jose

Thanks 4 this articule, just that i needed. I Will try yo implement it AND then a respond again.