XHR vs jQuery ajax vs get vs fetch

02/28/2018 10:21 ahmed1234550#1
which one should i use and why?
and what is the differents (im a beginner)


Code:
var xhr = new XMLHttpRequest();
xhr.onload = function() {alert(1)};
xhr.open("get", "http://--------.com", true);
xhr.send();
Code:
var xhr = new XMLHttpRequest();
xhr.addEventListener( "loadend", function() {alert(1)} );
xhr.open("GET", "http://--------.com", true);
xhr.send();
Code:
var request = $.ajax({
type: 'GET',
url: "http://--------.com",
async: true,
success: function() {alert(1);}
});
Code:
var request = $.get("http://--------.com").done(function() {
  alert(1);
});
Code:
fetch("http://--------.com").then(function(response) {
  alert(1);
});
Code:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {"done"}
}
xhr.open("GET", "http://--------.com", true);
xhr.send();
02/28/2018 14:28 iMostLiked#2
$.get(url) is equivalent to $.ajax({type: "GET", url: url}), so it's just a short form.
Whether you use $.get or $.ajax depends on how far you have to specify the request. With $.ajax you can pass some more options to the request.

$.ajax is the same as XHR, only made easier to use.

Fetch has some missing events in contrast to XHR, like:
- progress event
Code:
xhr.upload.onprogress = function(evt){
    // Math.round((evt.loaded / evt.total) * 100) + "%"
};
xhr.upload.onload = function(){
    // finished
};
- overriding content-type header of the response
...

I'd recommend using jquery's methods and if it's a simple request $.get.
02/28/2018 15:42 ahmed1234550#3
Quote:
Originally Posted by iMostLiked View Post
$.get(url) is equivalent to $.ajax({type: "GET", url: url}), so it's just a short form.
Whether you use $.get or $.ajax depends on how far you have to specify the request. With $.ajax you can pass some more options to the request.

$.ajax is the same as XHR, only made easier to use.

Fetch has some missing events in contrast to XHR, like:
- progress event
Code:
xhr.upload.onprogress = function(evt){
    // Math.round((evt.loaded / evt.total) * 100) + "%"
};
xhr.upload.onload = function(){
    // finished
};
- overriding content-type header of the response
...

I'd recommend using jquery's methods and if it's a simple request $.get.
thanks for your help i appreciate that, now i understand abit more
i have another question, so jquery is a library, ajax is doing the samething as xhr but behind the scenes to make it easier right?
02/28/2018 15:57 iMostLiked#4
Quote:
Originally Posted by ahmed1234550 View Post
thanks for your help i appreciate that, now i understand abit more
i have another question, so jquery is a library, ajax is doing the samething as xhr but behind the scenes to make it easier right?
Yes, correct!
02/28/2018 16:04 ahmed1234550#5
Quote:
Originally Posted by iMostLiked View Post
Yes, correct!
alright thanks for your help :)

#close
03/01/2018 18:41 Serraniel#6
Quote:
#close
^