top of page

What is the difference between $.ajax() and $.get()?

  • Quynh
  • Jul 2, 2017
  • 2 min read

I've noticed that $.ajax() and $.get() seem to be used interchangeably. For example, when I make a request to the GitHub API to list a user, it looks like get() and ajax() are giving me the exact same thing:

So what's the difference?

So yes, basically both methods perform the same thing - an asynchronous HTTP request. But you could say that $.ajax() is the more 'customizable' method, while $.get() is a shorthand version.

The most obvious difference is the syntax: you pass an object to $.ajax() and arguments to $.get(). This also means that with $.ajax() you have more options for configuring the settings. Examples:

  • set custom headers and pass in API token > use 'beforeSend' to set the function

  • a username and password can be sent to an HTTP authentication request > use "username" and "password"

  • error handling - when $.get() returns an error code, it will fails silently > use 'error' to set a function that is called when the request fails

  • set the HTTP method: GET/POST/PUT > use 'method' (default: GET)

$.get() is a simplified version of $.ajax(). Many settings that usually do not need to be specified in simple requests are set to default values. For example, the data is always returned to a callback function. It also only allows GET requests. In order to perform a POST request, you would use $.post().

And while we are at it - what is the difference to .load()?

.load() is similar to $.get() but it also allows you to define an element where you want to place the returned HTML. It has an implicit callback function. This means that even without passing in a callback function .load() takes care of inserting the data into the matched HTML element. It can be used like this:

$("#my-element").load("test.html")

This also means that .load() is only useful when the call results in HTML.

>> Overall, $.get(), $.post(), .load() are just wrappers for $.ajax(). The latter is always part of the former as it is called internally.

Comments


You Might Also Like:
IMG_20170609_201523
Screen Shot 2017-06-06 at 4.06.27 PM
Screen Shot 2017-06-11 at 11.45.13 AM
IMG_1521
IMG_20170518_185655
IMG_20170519_173940
IMG_20170515_164604
IMG_20170518_183205
IMG_20170518_183126
IMG_20170518_183254
IMG_20170503_153032
IMG_20170518_182930
IMG_20170519_074026
flatiron-school-51
IMG_20170518_183215
Hi,

I am Quynh. Recently, I took an exciting decision: I want to become a software developer.

Follow me on my journey! It starts at a coding bootcamp in New York...

 

Read More

 

bottom of page