Making Ajax Queries
Making Ajax Queries
Ajax/Fetch
Vyacheslav Koldovskyy
07/05/2018
Agenda
▪ Introduction to Ajax
▪ Using XMLHttpRequest object
▪ Ajax with jQuery
▪ Debugging AJAX Requests
▪ Live demo
▪ Links
Introduction to Ajax
What is Ajax?
▪ Ajax - acronym for Asynchronous JavaScript and XML
▪ Technically, Ajax is a set of web-development technologies
used on the client-side to create asynchronous web-
applications
▪ Web-applications with Ajax can send data to, and retrieve data
from, server asynchronously (in the background) without
interfering with the display and behavior of the existing page
▪ Ajax is widely used on modern web sites
Classic vs. Ajax Application
Communication Model
Same Origin Policy Limitation of Ajax
▪ Due to browser security restrictions, most Ajax
requests are subject to the same origin policy; the
request cannot successfully retrieve data from a
different domain, subdomain, port, or protocol.
▪ To overcome this restriction it is possible to use CORS
and JSONP
General Idea for XHR Usage
▪ XMLHttpRequest (XHR) object is the key to Ajax technology
▪ General idea of using XHR in Ajax:
2. Initialize XHR
properties with 3. Make 4. Handle
1. Create XHR
parameters of a request request result
request
▪ Note: Step 4 is asynchronous, this means that we don't suspend our code for
operation to complete, we pass callback function at step 2 and go further; it is
called when the request changes status or completes
Creating XMLHttpRequest object
▪ All modern browsers support the
XMLHttpRequest as native JS object. Syntax for
creating XHR as native JS object:
from a server
▪ The onreadystatechange event is triggered every time 2 – HEADERS_RECEIVED
▪ Comments:
– GET is simpler and faster than POST, and can be used in most cases
– Parameters should be transferred as part of URL address
– Maximum length of URL address limited, that is why it can't be used
for transferring volume data
– GET requests may be cached by browser
POST Request
▪ Sample 'POST' request:
xhr.open('POST', 'ajax_page.aspx', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('name=John&value=42');
▪ Comments:
– POST request is not limited in size, so it might be used for transferring volume data
– Parameters should be passed as argument for send() method
– Method setRequestHeader() should be used to define request headers for the
server to understand format of a request body
Server Response
▪ To get the response from a server, use one of
properties of the XMLHttpRequest object:
– responseText – get the response data as string, may be
used to transfer JSON data;
– responseXML – get the response data as XML data.
Sample Usage of responseXML
▪ In a sample below we assume that server returns some XML data about client:
<CLIENT>
<NAME>John</NAME>
<ADDRESS>Matrix Avenue</ADDRESS>
</CLIENT>
▪ We get XML data into JS object clientData of type XML Document and use it to fill some placeholders in our page
01 var xhr = getXHR();
02 xhr.onreadystatechange = function () {
03 if (xhr.readyState === 4 && xhr.status === 200) {
04 var clientData = xhr.responseXML;
05 document.getElementById('clientName').innerHTML =
06 clientData.getElementsByTagName('NAME')[0].childNodes[0].nodeValue;
07 document.getElementById('clientAddress').innerHTML =
08 clientData.getElementsByTagName('ADDRESS')[0].childNodes[0].nodeValue;
09 }
10 }
11 xhr.open('GET', 'user_data?id=1024', true);
12 xhr.send();
Demo 1: Ajax with Plain JavaScript
<!DOCTYPE html>
<html>
<head>
<script>
function getTextWithAjax() {
var xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById('target').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajax_info.txt', true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id='target'><h2>What is Ajax?</h2></div>
<button type='button' onclick='getTextWithAjax()'>Find out with Ajax</button>
</body>
</html>
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
Fetch API
Fetch API Sample
fetch('/users.json’)
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})
Fetch API Sample – POST
const form = document.querySelector('form’); fetch('/users', {
method: 'POST’,
fetch('/users', { headers: {
method: 'POST’, 'Content-Type': 'application/json’
body: new FormData(form) },
}) body: JSON.stringify({
name: 'Hubot’,
login: 'hubot’,
})
})
Ajax with jQuery
Methods of jQuery for Ajax Support
• main Ajax method of a jQuery library
.ajax() • provides numerous settings
• loads JSON-encoded data from the server using HTTP GET request
.getJSON() • supports JSONP that allows to overcome same origin policy
Method .load()
▪ Method .load() loads html code into some DOM element of a page
▪ Syntax: .load( url [, data] [,complete] )
– url: string containing the URL to which the request is set
– data: plain object or string that is sent to the server
– complete: a callback function that is executes when the request completes
▪ Sample:
$('#result').load('ajax/test.html');
▪ Method supports jQuery selectors passed after url address that determine the
content to be loaded.
▪ Sample:
$('#new-projects').load('/resources/load.html #projects li');
Method .get()
▪ Method .get() loads data from the server using HTTP GET
request
▪ Syntax: .get( url [, data ] [, success ] [, dataType ] )
– url – a string containing the URL to which the request is sent
– data - a plain object or string that is sent to the server with the request
– success - a callback function that is executed if the request succeeds
– dataType - the type of data expected from the server. Default: Intelligent Guess (xml, json,
script, or html).
01 $.get('example.php', function(data) {
02 $('body')
03 .append('Name: ' + data.name)
04 .append('Address: ' + data.address);
05 }, 'json')
06 .done(function() {
07 console.log('Request completed successfully');
08 });
Method .post()
▪ Method .post() loads data from the server using HTTP POST
request. Syntax is identical to shown before method .get().
▪ Syntax: .post( url [, data ] [, success ] [, dataType ] )
– url – a string containing the URL to which the request is sent
– data - a plain object or string that is sent to the server with the request
– success - a callback function that is executed if the request succeeds
– dataType - the type of data expected from the server. Default: Intelligent Guess (xml, json,
script, or html).
▪ https://jsfiddle.net/koldovsky/6pugnb57/1/
Debugging Ajax
Components of Ajax
Originally Ajax considered as based on the following
components:
– HTML (or XHTML) and CSS for presentation
– The Document Object Model (DOM) for dynamic display of and
interaction with data
– XML for the interchange of data, and XSLT for its manipulation
– The XMLHttpRequest (XHR) object for asynchronous communication
– JavaScript to bring these technologies together
Modern Ajax
▪ Modern paradigm of Ajax does not require all components
listed on the previous screen.
▪ For example, XML is not required for data interchange and,
therefore, XSLT is not required for the manipulation of data.
These components may be replaced by JSON (JavaScript
Object Notation).
▪ Also developers rarely use pure JavaScript code for Ajax
requests, it is far more convenient to use libraries like jQuery
or Prototype
Log XMLHttpRequest in Console
Breakpoints on XMLHttpRequest Events
To make breakpoints on XMLHttpRequest:
1. Click '+' button in XHR Breakpoints section;
2. Set URL filter in input field
1. Click button
function locationSuccess(position) {
var weatherAPI = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + position.coords.latitude +
'&lon=' + position.coords.longitude + '&callback=?';
$.getJSON(weatherAPI, function (response) {
$('#loc').html(response.city.name);
$('#temp').html(response.list[0].main.temp - 273.15);
});
}
function locationError(error) {
console.warn('Error:' + error.message);
}
</script>
</head>
<body>
<p>Location: <span id='loc'></span></p>
<p>Current temperature: <span id='temp'></span> °C</p>
</body>
</html>
Useful links
Links
▪ XMLHttpRequest on W3C: http://www.w3.org/TR/XMLHttpRequest/
▪ Official jQuery Website: http://jquery.com/
▪ Ajax Tutorial on W3Schools.com http://www.w3schools.com/ajax/
Advanced
Creating XHR for All Browsers
To handle modern and old browsers we should check if the browser supports XHR object and
create an instance of it, if not, create an ActiveXObject:
01 function getXHR() {
02 var xhr;
03 if (window.XMLHttpRequest) {
04 // code for IE7+, Firefox, Chrome, Opera, Safari
05 xhr = new XMLHttpRequest();
06 } else {
07 // code for IE6, IE5
08 xhr = new ActiveXObject('Microsoft.XMLHTTP');
09 }
10 return xhr;
11 }
Method .ajax()
▪ Method .ajax() is the main Ajax method of jQuery library, it accepts:
1) one argument that is plain object with numerous fields containing all settings for method call
2) or two arguments: first is the url and second is the settings object
▪ Syntax:
1) .ajax( settings )
2) .ajax( url [, settings] )
▪ Returns: method returns jqXHR object, which is superset to XMLHTTPRequest and supports
additional methods that calls after request completes and may be linked to each other:
– .done(function( data, textStatus, jqXHR ) {});
– .fail(function( jqXHR, textStatus, errorThrown ) {});
– .always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
Object settings for jQuery.ajax
Some important fields of settings object passed as a parameter to .ajax() method:
▪ url – an address of the request
▪ data – transferred data (object or string)
▪ dataType – type of return data passed in callback function (xml, html, script, json, jsonp, text)
▪ type – request type (GET or POST)
▪ async – make asynchronous request (true by default)
▪ cache – enable data caching by browser (true by default)
▪ timeout – timeout of a request in milliseconds
▪ beforeSend – callback function to run before request sending
▪ error – callback function to run on error
▪ success – callback function to run on success result of a request
▪ complete – callback function to run when request completes
Example of .ajax() Method Call
In an example below we make POST request to some url 'getdata'; while making the
request we send contents of element with id 'dataForm' and set data type to html; in
case of success we convert request result into jQuery object, modify data by removing
last element of a list and append modified data to some element with id 'target'
01 $.ajax({
02 type: 'POST',
03 url: 'getdata',
04 data: $('#dataForm').serialize(),
05 dataType: 'html',
06 success: function (data) {
07 var jqObj = jQuery(data);
08 jqObj.find('li:last').remove();
09 $('#target').empty().append(jqObj);
10 }
11 });
How to Detect Ajax Request on Server Side?
▪ To detect if request from a client is an Ajax request we should
use HTTP_X_REQUESTED_WITH field on a server-side
▪ This field is set only when XMLHttpRequest object used to
make a request, it's natively supported by modern browsers
▪ Most server-side frameworks provide special property to check
for Ajax request that internally uses HTTP_X_REQUESTED_WITH
field
Thank you!