# 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 |
$.ajax()
can handle all the different HTTP verb methodes (opens new window) you can expect from a CRUD (Create, Read, Update and Delete)
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 theget
,post
,patch/put
ordelete
requestdata
(optional): an object or string that is sent to the server with the requestsuccess
(optional): a callback function that is executed if the request succeedsdataType
(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
2
3
4
5
# Chainable methodes
- Every shorthand methode can be chained with so-called deferred objects (opens new window)
- The most useful deferred objects (methodes) are:
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()
orthen()
methodes - Any errors (rejected state) can be intercepted with both
catch()
orfail()
.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
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
HTML
$.getJSON() v1
$.getJSON() v2
$.getJSON() v3
$.get()
$.ajax()
result
<div class="border-gray row" id="users"></div>
Copied!
1
# POST
- Use the
$.post()
or the$.ajax()
methode with thetype: 'POST'
to send new data to an API or insert something in a database - Open jquery/ajax/post.html and jquery/ajax/post.js
HTML
$.post()
$.ajax()
result
<div class="border-gray row" id="user"></div>
Copied!
1
# PATCH/PUT
- Use the
$.ajax()
methode withtype: 'PATCH'
ortype: 'PUT'
to update data through an API or update something in a database - Open jquery/ajax/patch.html and jquery/ajax/patch.js
HTML
$.ajax()
result
<div class="border-gray row" id="user"></div>
Copied!
1
# DELETE
- Use the
$.ajax()
methode withtype: 'DELETE'
to delete data through an API or delete something from a database - Open jquery/ajax/delete.html and jquery/ajax/delete.js
HTML
$.ajax()
result
<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
- Open /jquery/ajax/images.html and /jquery/ajax/images.js
- In this example we fetch all images from our own (fake) API:
https://my-json-server.typicode.com/pverhaert/itf-api/picsum (opens new window)
HTML
$.getJSON()
result
<div class="spinner tertiary"></div> <div class="row" id="imgContainer"></div>
Copied!
1
2
2
# Fetch movie info
- Open /jquery/ajax/omdb.html and /jquery/ajax/omdb.js
- In this example we fetch movie information from the OMDb API (opens new window)
- The parameters we needed are:
apikey
: your API key (you must first generate a free apikey (opens new window))t
: the movie title to search fory
: year of releaseplot
: can befull
orshort
- The JSON we get from te server: https://www.omdbapi.com/?apikey=yourKey&t=Pulp+fiction&y=&plot=short (opens new window)
(ReplaceyourKey
in the query string with a real API key)
HTML
JavaScript
result
- 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
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