# AJAX

  • AJAX was the acronym for Asynchronous JavaScript And XML
  • In the meantime, the description of AJAX is already outdated because we can import not only XML, but also text, HTML, JSON and JavaScript
  • The $.ajax() method is jQuery's low-level AJAX implementation, and it's the counterpart of the fetch API in vanilla JS
  • $.ajax() is the most comprehensive, but also the most difficult method
  • Fortunately, there are also shorthand methods with fewer bells and whistles, but which are much easier to understand and use
  • The table below gives an overview of the most used methods with their capabilities and limitations

# AJAX methodes

jQuery AJAX methode verb dataType remark
$.ajax(url [,settings ]) (opens new window) GET, POST, PATCH/PUT, DELETE json, xml, text, script, html perform an asynchronous HTTP (Ajax) request
$.get(url [,data ] [,success ] [,dataType ]) (opens new window) GET json, xml, text, script, html shorthand methode for $.ajax() with GET request
$.getJSON(url [,data ] [,success ]) (opens new window) GET json shorthand methode for $.get() with GET request and JSON as datatype
$.post(url [,data ] [,success ] [,dataType ]) (opens new window) POST json, xml, text, script, html shorthand methode for $.ajax() with POST request
verb (methode) action description
GET read get date from an API, database, ...
POST create post date to an API, add data to a database, ...
PATCH/PUT update update a record in the database, ...
DELETE delete delete a record from the database, ...
  • Every shorthand methode must have at least one parameter, the other parameters are optional
    • url (required): the url that handels the get, post, patch/put or delete request
    • data (optional): an object or string that is sent to the server with the request
    • success (optional): a callback function that is executed if the request succeeds
    • dataType (optional): the type of data expected from the server (if omitted, jQuery tries to guess the dataType)

TIP

Use jQuery's .serialize() (opens new window) methode to URL-encode all form elements for data submission. E.g.



 



$('form').submit(function(e) {
  e.preventDefault();
  const data = $(this).serialize();
  console.log('data', data);
});
Copied!
1
2
3
4
5

# Chainable methodes

methode description
.done(cb [, cb]) (opens new window) run one or more callback functions when the data is resolved
.catch(cb) (opens new window) run a callback function when the data is rejected
.fail(cb [, cb]) (opens new window) run one or more callback functions when the data is rejected
.then(resolveCb [, rejectCb] [, progressCb]) (opens new window) run one or more callback functions when the data is resolved, rejected, or still in progress
.always(cb [, cb]) (opens new window) run one or more callback functions when the data is resolved or rejected

REMARKS

  • As soon as you receive data from e.g. an API (resolved state), you can process this data in the default callback function of the AJAX methode or in one or more done() or then() methodes
  • Any errors (rejected state) can be intercepted with both catch() or fail()
  • .always() is a very handy methode to hide e.g. a preloader because this methode runs both after a resolved state or after a rejected state
  • The .then() method accepts a resolved and a rejected callback and is equivalent to using done/fail together, such that:
$.ajax().then(resolveCb, rejectCb);
// is equivalent to
$.ajax().then(resolveCb, rejectCb);
Copied!
1
2
3

# Basic HTTP verbs

  • To demonstrate a very basic example of the different verbs, we use the https://reqres.in/ (opens new window) API
  • This is a fake API where the create, update and delete actions are not actually taking place, but the response 'fakes' this is really happens

# GET

  • Use the $.getJSON() (recommended), $.get() or $.ajax() (the hard way) methode to retrieve JSON data from an API or from a database
  • Open jquery/ajax/get.html and jquery/ajax/get.js
  • This example gets all the users on page 2 with this URL: https://reqres.in/api/users?page=2 (opens new window)
  • We are only interested in the key data witch contains an array of six users
<div class="border-gray row" id="users"></div>
Copied!
1

# POST

  • Use the $.post() or the $.ajax() methode with the type: 'POST' to send new data to an API or insert something in a database
  • Open jquery/ajax/post.html and jquery/ajax/post.js
<div class="border-gray row" id="user"></div>
Copied!
1

# PATCH/PUT

  • Use the $.ajax() methode with type: 'PATCH' or type: 'PUT' to update data through an API or update something in a database
  • Open jquery/ajax/patch.html and jquery/ajax/patch.js
<div class="border-gray row" id="user"></div>
Copied!
1

# DELETE

  • Use the $.ajax() methode with type: 'DELETE' to delete data through an API or delete something from a database
  • Open jquery/ajax/delete.html and jquery/ajax/delete.js
<div class="border-gray row" id="user"></div>
Copied!
1

# Examples

As we will not be using a backend of our own in this course, we will only discuss examples where we are retrieving data from external API's

# Fetch images

 
 

<div class="spinner tertiary"></div>
<div class="row" id="imgContainer"></div>
Copied!
1
2

# Fetch movie info

  • line 2: replace the value for apikey with your API key
  • As you can see in the form, the name attribute of the form elements matches exactly the keys for the query string we have to append to the fetch URL
  • This makes it super easy (only three lines of code) to serialize the form (opens new window) with JavaScript
    The result of this serialization is a string like this: apikey=yourKey&t=Pulp+fiction&y=&plot=short

 



 





 





 








 
 

<form>
    <input type="hidden" name="apikey" value="yourKey" />
    <div class="row responsive-label">
        <div class="col-sm-12 col-md-2"><label for="title" class="doc">Title</label></div>
        <div class="col-sm-12 col-md">
            <input type="text" placeholder="Title" id="title" name="t" value="Pulp fiction" required />
        </div>
    </div>
    <div class="row responsive-label">
        <div class="col-sm-12 col-md-2"><label for="year">Year</label></div>
        <div class="col-sm-12 col-md">
            <input type="number" placeholder="Year" id="year" name="y" />
        </div>
    </div>
    <div class="row responsive-label">
        <div class="col-sm-12 col-md-2"><label for="plot">Plot</label></div>
        <div class="col-sm-12 col-md">
            <select id="plot" name="plot">
                <option value="short">short</option>
                <option value="full">full</option>
            </select>
            <button type="submit" class="primary">Search</button>
        </div>
    </div>
</form>
<hr />
<div class="spinner tertiary"></div>
<div class="row" id="movieContainer"></div>
Copied!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Last Updated: 6/23/2021, 1:59:14 PM