Files
freeCodeCamp/guide/english/jquery/jquery-ajax-get-method/index.md
qhieu45 c6e4efc268 Update error handling instruction in $.get (#28838)
Add example to handle error when calling $.get
2019-06-27 18:58:34 -07:00

2.4 KiB

title
title
jQuery Ajax Get Method

jQuery Ajax Get Method

Sends an asynchronous http GET request to load data from the server. Its general form is:

jQuery.get( url [, data ] [, success ] [, dataType ] )
  • url: The only mandatory parameter. This string contains the address to which to send the request. The returned data will be ignored if no other parameter is specified.
  • data: A plain object or string sent to the server with the request.
  • success: A callback function executed if the request succeeds. It takes as an argument the returned data. It is also passed the text status of the response.
  • dataType: The type of data expected from the server. The default is Intelligent Guess (xml, json, script, text, html). If this parameter is provided, the success callback also must be provided.

Examples

Request resource.json from the server, send additional data, and ignore the returned result:

$.get('http://example.com/resource.json', {category:'client', type:'premium'});

Request resource.json from the server, send additional data, and handle the returned response (json format):

$.get('http://example.com/resource.json', {category:'client', type:'premium'}, function(response) {
     alert("success");
     $("#mypar").html(response.amount);
});

However, $.get doesn't provide any way to handle error.

The above example (with error handling) can also be written as:

$.get('http://example.com/resource.json', {category:'client', type:'premium'})
     .done(function(response) {
           alert("success");
           $("#mypar").html(response.amount);
     })
     .fail(function(error) {
           alert("error");
           $("#mypar").html(error.statusText);
     });

jQuery.ajax()

$.get( url [, data ] [, success ] [, dataType ] ) is a shorthand Ajax function, equivalent to:

$.ajax({
     url: url,
     data: data,
     success: success,
     dataType: dataType
});

$.ajax() provides plenty of additional options, all of which are located here.

More Information:

For more information, please visit the official jQuery.get website.