AJAX
class: center, middle .title[ Front-end training # AJAX ] --- # HTTP The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.
Hypertext is structured text that uses logical links (hyperlinks) between nodes containing text. HTTP is the protocol to exchange or transfer hypertext. --- # HTTP Request ``` method: POST url: "https://twitter.com/i/users/prompts/impress" scheme: https accept: application/json, text/javascript, */*; q=0.01 accept-encoding: gzip, deflate, br accept-language: en-US,en;q=0.8,ru;q=0.6,uk;q=0.4 content-length: 74 content-type: application/x-www-form-urlencoded; charset=UTF-8 cookie: goth=1; lang=en; auth_token=fce0edb20d53fa9cce1666d511b2e2a115fadf45; ``` --- # HTTP Response ``` status: 200 cache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0 content-encoding: gzip content-length: 44 content-type: text/javascript; charset=utf-8 date: Thu, 04 Aug 2016 14:07:57 GMT expires: Tue, 31 Mar 1981 05:00:00 GMT last-modified: Thu, 04 Aug 2016 14:07:57 GMT set-cookie: _twitter_sess=BAh7CzoJdXNlcmkEBYZVBzoPY3J; ``` --- # AJAX AJAX(Asynchronous JavaScript and XML) is only a name given to a set of tools that were previously existing. The main part is XMLHttpRequest, a server-side object usable in JavaScript, that was implemented into Internet Explorer since the 4.0 version. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. --- # AJAX transports There ara couple Javascript object or HTML tags that can provide server-client comunication: - XMLHttpRequest - Iframe - Script --- # Data formats - Text ``` elem.innerText = xhr.responseText ``` - HTML ``` elem.innerHTML = xhr.responseText ``` - XML Server should set "Content-Type: text/xml" ``` var xml = xhr.responseXML ``` - JSON (Javascript Object Notation) ``` var obj = JSON.parse(responseText); ``` - JSONP ``` callback({{ "response": { "size": "370", "price":"200" }}}) ``` --- # XMLHttpRequest **XMLHttpRequest** is a JavaScript object that was designed by Microsoft and adopted by Mozilla, Apple, and Google. It's now being standardized in the W3C. It provides an easy way to retrieve data at a URL. Despite its name, ***XMLHttpRequest*** can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp). --- # XMLHttpRequest usage ``` function vote(outputElem) { var xhr = new XMLHttpRequest(); xhr.open('GET', '/api/lessons/ajax/vote'); xhr.onreadystatechange = function() { if (xhr.readyState != 4) return; //return if not complete if (xhr.status != 200) { //check request status alert('Error ' + xhr.status + ': ' + xhr.statusText); return; } outputElem.innerHTML = xhr.responseText; // process result } outputElem.innerHTML = '...'; xhr.send(); } ``` --- # XMLHttpRequest event handlers |||| |--- |--- | | readystatechange | The readyState attribute changes value, except when it changes to UNSENT. | | loadstart | The fetch initiates. | | progress | Transmitting data. | | abort | When the fetch has been aborted. For instance, by invoking the abort() method. | | error | The fetch failed. | | load | The fetch succeeded. | | timeout | The author specified timeout has passed before the fetch completed. | | loadend | The fetch completed (success or failure). | --- # XMLHttpRequest FormData FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the ***XMLHttpRequest send()*** method. ```html
``` ``` // create object from form var form = document.forms.user; var formData = new FormData(form); // add another kay-value pair formData.append("lastname", "Pupkin"); // send var xhr = new XMLHttpRequest(); xhr.open("POST", "/url"); xhr.send(formData); ``` .small[ ***Browsers***: all, except IE< 10 ] --- # WebSocket The WebSocket specification - developed as part of the HTML5 initiative - introduced the WebSocket JavaScript interface, which defines a full-duplex single socket connection over which messages can be sent between client and server. The WebSocket standard simplifies much of the complexity around bi-directional web communication and connection management. WebSocket represents the next evolutionary step in web communication compared to Ajax. ``` ws = new WebSocket("ws://example.com/demo"); ws.onopen = function() { alert("Connection opened...") }; ws.onclose = function() { alert("Connection closed...") }; // 'onmessage' invoked every time the browser receives data ws.onmessage = function(evt) { $("#msg").append("
"+evt.data+"
"); }; ws.send("Hello world"); ``` --- # SOP & CORS The [same-origin policy](https://en.wikipedia.org/wiki/Same-origin_policy) restricts how a document or script loaded from one origin can interact with a resource from another origin. It is a critical security mechanism for isolating potentially malicious documents. A resource makes a [cross-origin request](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) when it requests a resource from a different domain than the one which the first resource itself serves. --- # JSONP **JSONP** (JSON with Padding) is a technique used by web developers to overcome the cross-domain restrictions imposed by browsers to allow data to be retrieved from systems other than the one the page was served by. ```html ``` ``` parseResponse({ "response": { "size": "370", "price":"200" }}) ``` ``` function parseResponse(data) { console.log(data.response); } ``` The typical use of JSONP provides cross-domain access to an existing JSON API, by wrapping a JSON payload in a function call. --- # Resources - http://json.org/ - https://xhr.spec.whatwg.org/ - https://en.wikipedia.org/wiki/Same-origin_policy - https://en.wikipedia.org/wiki/Cross-origin_resource_sharing - http://www.html5rocks.com/en/tutorials/cors/