The Ajax Shorthand Methods JQ Home  <<  JQ Advanced  <<  The Ajax Shorthand Methods

In this lesson we investigate the Ajax jQuery Shorthand Methods.

All the Ajax shorthand methods call the jQuery.ajax() method under the bonnet, but when we just want to do simple requests the Ajax shorthand methods are a much easier way of doing this. You can always use the jQuery.ajax() method for fine-grained control of requests when its necessary.

jQuery Ajax methods return a jqXHR object which is a superset of the browser's native XMLHttpRequest object. The jqXHR object implements the Promise interface, giving it all the properties, methods, and behavior of a Promise as discussed in The Deferred Object lesson.

  • A jqXHR object will expose the following properties and methods for backward compatibility with the XMLHttpRequest object:
    jqXHR Object Description
    Methods
    abort()Cancels the currently executing request.
    getAllResponseHeaders()Returns a string containing the names and value of all response headers.
    getResponseHeader(name)Returns the value of the specified response headers.
    .overrideMimeType()Used in the beforeSend() callback function, to modify the response content-type header.
    setRequestHeader(name, value)Set a request header using the specified name and value.
    Properties
    readyStateAn integer indicating the current state of the request.
    responseTextUnderlying request responded with text.
    responseXMLUnderlying request responded with xml.
    statusResponse status code returned from the server.
    statusTextStatus text message returned by the response.

Ajax Shorthand Methods

The five methods which make up the jQuery Ajax Shorthand Methods are listed in the table below, click a link to go to examples for that method.

Shorthand Methods Description
jQuery.get()Load data from the server, using a HTTP GET request.
jQuery.getJSON()Load data from the server, that has been JSON encoded, using a HTTP GET request.
jQuery.getScript()Load and execute a JavaScript file from the server, using a HTTP GET request.
jQuery.post()Load data from the server, using a HTTP POST request.
.load()Load data from the server and populate the matched element from the returned HTML on successful completion.

The jQuery.get() Method Top

Load data from the server, using a HTTP GET request.

This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax() method as follows:


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

We will be using this methods only signature jQuery.get( url [, data] [, function(data, textStatus, jqXHR)] [, dataType] ) for our example which will load data from the server, using a HTTP GET request.

When we press the left button the first time, we use the jQuery.get() method in its simplest form just using a url and output some messages dependant upon request success.

When we press the right button the first time, we use the jQuery.get() method with a url and a success handler and output some messages dependant upon request success.


$(function(){
  $('#btn1').one('click', function(){
    $.get( "../../../js/get1.js" )
      .done(function() { $('#div1').append('get request succeeded! <br>'); })
      .fail(function() { $('#div1').append('Request failed! <br>'); })
      .always(function() { $('#div1').append('Request ended! <br><br>'); 
    });
  });
  $('#btn2').one('click', function(){
    $.get( "../../../js/get1.js", function(data, textStatus, jqXHR) {
         $('#div1').append('The request was a sucesss! <br>');
      })
      .done(function() { $('#div1').append('Request succeeded! <br>'); })
      .fail(function() { $('#div1').append('Request failed! <br>'); })
      .always(function() { $('#div1').append('Request ended! <br><br>'); 
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../../../js/get1.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div1').append('Message from get1.js: ' + someText + '<br>');
});

div1. Some initial text.

Press the button below to action the above code:

               

The jQuery.getJSON() Method Top

Load data from the server, that has been JSON encoded, using a HTTP GET request.

This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax() method as follows:


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

We will be using this methods only signature jQuery.getJSON( url [, data] [, function(data, textStatus, jqXHR)] ) for our example which loads data from the server, that has been JSON encoded, using a HTTP GET request.

When we press the button the first time, we use the jQuery.getJSON() method with a url and a success handler. We interrogate the returned JSON data and move it to an array before appending it to our page.


$(function(){
  $('#btn5').one('click', function(){
    $.getJSON('../pages/testfileb.json', function(data) {
      var sayingsList = [];

      $.each(data, function(key, val) {
        sayingsList.push('<li>' + val + '</li>');
      });

      $('<ul/>', {
        html: sayingsList.join('')
      }).appendTo('#div4');
    });
  });
});

/*
 * The external JSON file called from $.getJSON() (url: "../pages/testfileb.json")
 * is shown below.
 */
{
  "1": "A stitch in time saves nine",
  "2": "The quick brown fox jumps over the lazy dog",
  "3": "10 green bottles",
  "4": "Blood is thicker than water",
  "5": "A bird in the hand is worth two in the bush",
  "6": "Prevention is better than cure",
  "7": "To be or not to be"
}

div4. Some initial text.

Press the button below to action the above code:

The jQuery.getScript() Method Top

Load and execute a JavaScript file from the server, using a HTTP GET request.

This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax() method as follows:


$.ajax({
  url: url,
  dataType: 'script',
  data: data,
  cache: false,
  success: callback
});

We will be using this methods only signature jQuery.getScript( url [, function(data, textStatus, jqXHR)] ) for our example which loads and execute a JavaScript file from the server, using a HTTP GET request.

When we press the left button the first time, we use the jQuery.getScript() method with a url. The script for the 'get5.js' asset executes and appends a message to this page.

When we press the right button the first time, we use the jQuery.getScript() method with a url and a success handler. The script for the 'get5.js' asset executes and appends a message to this page and the success callback is invoked and also appends a message.


$(function(){
  $('#btn6').one('click', function(){
    $.getScript( "../../js/get5.js" )
  });
  $('#btn7').one('click', function(){
    $.getScript( "../../js/get5.js", function() {
      $('#div3').append('The request was a sucesss! <br>');
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../../js/get5.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div3').append('Message from get5.js: ' + someText + '<br>');
});

div3. Some initial text.

Press the button below to action the above code:

             

The jQuery.post() Method Top

Load data from the server, using a HTTP POST request.

This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax() method as follows:


$.ajax({
  type: 'POST',
  url: url,
  dataType: dataType,
  data: data,
  success: callback
});

We will be using this methods only signature jQuery.post( url [, data] [, function(data, textStatus, jqXHR)] [, dataType] ) for our example which will load data from the server, using a HTTP POST request.

When we press the left button the first time, we use the jQuery.post() method in its simplest form just using a url and output some messages dependant upon request success.

When we press the right button the first time, we use the jQuery.post() method with a url and a success handler and output some messages dependant upon request success.


$(function(){
  $('#btn8').one('click', function(){
    $.post( "../../js/post1.js" )
      .done(function() { $('#div5').append('Post request succeeded! <br>'); })
      .fail(function() { $('#div5').append('Post request failed! <br>'); })
      .always(function() { $('#div5').append('Post request ended! <br><br>'); 
    });
  });
  $('#btn9').one('click', function(){
    $.post( "../../js/post1.js", function(data, textStatus, jqXHR) {
      $('#div5').append('The post request was a sucesss! <br>');
    })
      .done(function() { $('#div5').append('Post request succeeded! <br>'); })
      .fail(function() { $('#div5').append('Post request failed! <br>'); })
      .always(function() { $('#div5').append('Post request ended! <br><br>'); 
    });
  });
      .always(function() { $('#div5').append('Request ended! <br><br>'); 
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../../js/post1.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div5').append('Message from post1.js: ' + someText + '<br>');
});

div5. Some initial text.

Press the button below to action the above code:

               

The .load() Method Top

Load data from the server and populate the matched element from the returned HTML on successful completion.

This is a shorthand Ajax function, which is equivalent using the jQuery.ajax() method as follows:


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

We will be using this methods only signature .load( url [, data] [, function(responseText, textStatus, XMLHttpRequest)] ) for our example which will load data from the server and populate the matched element from the returned HTML on successful completion.

When we press the button the first time, we use the .load() method in its simplest form just using a url and load some HTML from another server page onto this page. The data is loaded to the element with an id of '#sayings', the select input field below is populated.


$(function(){
  $('#btn3').one('click', function(){
    $('#sayings').load( "../pages/testFile.html" );
  });
});
/*
 * The code for the external HTML file called from $.load() (url: "../pages/testfile.html)
 * is shown below.
 */
<option value="">— choose a saying —</option>
<option value="1">A stitch in time</option>
<option value="2">The quick brown fox</option>
<option value="3">10 green bottles</option>
<option value="4">Blood is thicker than water</option>
<option value="5">A stitch in time saves nine</option>
<option value="6">A bird in the hand</option>
<option value="7">Prevention is better than cure</option>
<option value="8">To be or not to be</option>

Old Sayings

Saying list to load up:

 

Press the button below to action the above code:

Lesson 9 Complete

In this lesson we looked at the Ajax Shorthand Methods.

Related Tutorials

jQuery Advanced - Lesson 8: Ajax Low-Level Interface
jQuery Advanced - Lesson 10: Ajax Helper Functions
jQuery Advanced - Lesson 11: Ajax Global Event Handlers

Reference

Methods

Events - .on() method
Events - .one() method
Manipulation - .ppend() method
Ajax Shorthand Methods- jQuery.get method
Ajax Shorthand Methods - jQuery.getJSON() method
Ajax Shorthand Methods - jQuery.getScript() method
Ajax Shorthand Methods - .load() method
Ajax Shorthand Methods - jQuery.post() method