Why would you use a fetch get request instead of a jquery Get Request?

Why would you use a fetch get request instead of a jquery Get Request?
0.0 0

#1

I am currently not ready to do the Free code camp exercises so I decided to learn the basics at code academy. In fact, I tried free code camp and did all the way through javascript (not objects). Because I did not know the syntax at the time, I really struggled.

With that in mind, I want to know why I am learning about fetch GET in addition to GET requests;

I’ve read the psuedocode associated with both:

Here is a fetch GET request:

Fetch GET
 fetch('https://api-to-call.com/endpoint').then(
response => { 
	if (response.ok) {
   return response.json(); 
 }
  throw new Error('Request failed!');
}, networkError => {
 console.log(networkError.message);
}).then(jsonResponse => jsonResponse);

Here is a jquery get request (It’s a different format anyway, both could be jquery)

 $.ajax({
   url: 'https://api-to-call.com/endpoint', 
         type: 'GET',
         dataType: 'json',
         success (response){'https://api-to-call.com/endpoint'},
         error (jqXHR, status, errorThrown){},
         
 });

Note that both of these are correct but I dont really understand what I’m working towards.
On the side, I am working on a project that will require me to send information and the IP to return info to me.

I would be very appreciative of any thoughts that anyone with some experience would have regarding this issue.


#2

Both of your snippets do mainly the same thing. The fetch API is relatively new (at least older than jQuery) and is native to Javascript: that is, you can still use it if you aren’t using jQuery.

While I personally prefer the request library Axios, many developers us fetch to do HTTP requests, either because they like it more or because jQuery is not avaiblable. For example, you could be working on a React app where jQuery is not installed as a dependency.


#3

So it sounds like that there may be some cases in which you would be screwed if you did not know another option?


#4

? Still curious if what I am saying is correct?


#5

While jQuery is still popular, its use has been decreasing with the rise of Javascript frameworks like Backbone, AngularJS and later Angular2, React and Vue. So if you join a project where one of these frameworks is used, you cannot rely on jQuery being available to make HTTP requests to the server or some API. Anyways, besides the fetch API there are many libraries that do this. I personally prefer axios:


#6

Fetch is a new way of doing requests. You can see which browsers support it on this very useful website: https://caniuse.com/#search=fetch

The old way is doing by using XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

The old way is safer, because older browser versions still use it.

jQuery’s $.ajax request is just a wrapper of javascript’s XMLHttpRequest.