What is the difference between XMLHttpRequest, jQuery.ajax, jQuery.post, jQuery.get
How can I find out which method is best for a situation? Can anybody provide some examples to know the difference in terms of functionality and performance?
XMLHttpRequest
is the raw browser object that jQuery wraps into a more usable and simplified form and cross browser consistent functionality.jQuery.ajax
is a general Ajax requester in jQuery that can do any type and content requests.jQuery.get
andjQuery.post
on the other hand can only issue GET and POST requests. If you don't know what these are, you should check HTTP protocol and learn a little. Internally these two functions usejQuery.ajax
but they use particular settings that you don't have to set yourself thus simplifying GET or POST request compared to usingjQuery.ajax
. GET and POST being the most used HTTP methods anyway (compared to DELETE, PUT, HEAD or even other seldom used exotics).
All jQuery functions use XMLHttpRequest
object in the background, but provide additional functionality that you don't have to do yourself.
Usage
So if you're using jQuery I strongly recommend that you use jQuery functionality only. Forget about XMLHttpRequest
altogether. Use suitable jQuery request function variations and in all other cases use $.ajax()
. So don't forget there are other common jQuery Ajax related functions to $.get()
, $.post()
and $.ajax()
. Well you can just use $.ajax()
for all of your request, but you will have to write a little more code, because it needs a bit more options to call it.
Analogy
It's like you would be able to buy yourself a car engine that you'd have to create a whole car around it with steering, brakes etc... Car manufacturers produce completed cars, with a friendly interface (pedals, steering wheel etc.) so you don't have to do it all yourself.
Each one of them uses XMLHttpRequest. This is what the browser uses to make the request. jQuery is just a JavaScript library and the $.ajax method is used to make a XMLHttpRequest.
$.post and $.get are just shorthand versions of $.ajax
. They do pretty much the same thing but makes it quicker to write an AJAX request - $.post
makes a HTTP POST request and $.get
makes a HTTP GET request.