Reputation: 679
I just started learning Ajax, and most people as I saw working with Ajax (making Get and Post requests) like this:
$.ajax({
method: "GET",
url: "Customers/GetCustomerById",
data: { customerId: Id }
})
.done(function (response) {
//Do something here
});
I red behind Ajax is XMLHttpRequest object
, so does that means when code above is used, something like this is happening "behind the scene" :
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function someMyFunction(){
// Process the server response here.
};
http.open("GET", url+"?"+customerId, true);
Is this true?
And is this second approach avoided today? Or it's still being used? I'm just learning web and I don't know so that's reason why I'm asking..
And I'm wondering also why people are using this "first" approach, maybe they are not but I acctually saw it on many places...
Thanks a lot guys and cheers!
Upvotes: 1
Views: 364
Reputation: 109
"First" approaches uses a js library called jQuery. Not only is it easier to make ajax calls using jQuery (which is not the primary use of jQuery), but it also handles ajax calls across different browsers and mainly different versions of browsers. The XMLHTTPRequest object are supported by most browsers today. But that is not the case with older browsers.
Read this for more info.
It may be easier to code using jQuery but there are times when conflicts between files occuring because of jQuery (or some browsers may have issues with jQuery). And in those situations developers may choose to implement and handle these and/or other scenarios themselves by coding in vanilla javascript. Choosing either approach is up to the developer.
Hope this answer helps.
Upvotes: 0
Reputation: 1146
I will describe the answer simply in two sections
1. Behind the Scenes of $.ajax()
Yeah basically JQuery uses the native browser API for Ajax Requests. It creates XHR object same as your second code but they used some additional lines of code because JQuery handles not only plain text. (ie. additional JSON and XML Support)
You may see the JQuery source code portion for XHR here to watch more behind the scenes ;)
2. Use of Native browser API
The second example code type is nowadays also using. People use $.ajax()
since it makes coding fast and easy also very easy to capture XML and JSON responses.
Hope it helps
Upvotes: 2
Reputation: 943142
I red behind Ajax is XMLHttpRequest object
XHR is one browser API used to perform Ajax. There are several others. XHR is probably most commonly used.
Is this true?
jQuery does do something along those lines behind the scenes.
And is this second approach avoided today?
No.
Some people use jQuery because they find it more convenient than using the native browser APIs or another library. Other people do not use jQuery.
Upvotes: 1