JS

AJAX

Agenda

  1. Networking
  2. AJAX

Client/server model of communication

WEB

Web inventor Tim Berners-Lee helped found, the World Wide Web Consortium (W3C): "The World Wide Web is the universe of network-accessible information, an embodiment of human knowledge."

Main Components:

URL is an acronym that stands for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.

HTTP HyperText Transfer Protocol. HTTP is the underlying protocol used by the World Wide Web and this protocol defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.

HTML(HyperText Markup Language) is a descriptive language that specifies webpage structure.

IP Internet Protocol

Protocol by which data is sent from one computer to another on the Internet

Each computer (known as a host) on the Internet has at least one IP address that uniquely identifies it from all other computers on the Internet.

  • dynamic is an IP address that dynamically assigned to your computer each time your computer (or router) is rebooted
  • static does not change even if your computer reboots
  • public IP address that can be accessed over the Internet
  • private for private networks

Application layer

  • HTTP Hypertext Transfer Protocol
  • DNS Domain Name System
  • DHCP Dynamic Host Configuration Protocol
  • SMTP Simple Mail Transfer Protocol
  • POP3 Post Office Protocol
  • Telnet terminal network
  • SSH Secure Shell cryptographic network protocol
  • FTP File Transfer Protocol
  • TFTP Trivial File Transfer Protocol

HTTP

Set of rules for transferring files (text, graphic images, sound, video, and other multimedia files) on the World Wide Web

HTTP Methods

Two commonly used methods for a request-response between a client and server

GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource

Other HTTP Request Methods:

  • HEAD Same as GET but returns only HTTP headers and no document body
  • PUT Uploads a representation of the specified URI
  • DELETE Deletes the specified resource
  • OPTIONS Returns the HTTP methods that the server supports
  • CONNECT Converts the request connection to a transparent TCP/IP tunnel

HTTP Status Codes

  • 1xx Informational
  • 2xx Success 200 OK
  • 3xx Redirection
  • 4xx Client Error 400 Bad Request 401 Unauthorized 402 Payment Required 403 Forbidden 404 Not Found
  • 5xx Server Error 500 Internal Server Error

REST (Representational state transfer)

  • Client–server – The client handles the front end the server handles the backend and can both be replaced independently of each other.
  • Stateless – No client data is stored on the server between requests and session state is stored on the client.
  • Cacheable – Clients can cache response (just like browsers caching static elements of a web page) to improve performance.

CRUD

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

  • fetch

XMLHttpRequest usage

// 1. Создаём новый объект XMLHttpRequest
var xhr = new XMLHttpRequest();

// 2. Конфигурируем его: GET-запрос на URL 'data.json'
// синхронная обработка
xhr.open('GET', 'data.json or www', false);

// 3. Отсылаем запрос
xhr.send();

// 4. Если код ответа сервера не 200, то это ошибка
if (xhr.status !== 200) {
    // обработать ошибку
    console.log( 'error', xhr.status + ': ' + xhr.statusText ); 
    // пример вывода: 404: Not Found
} else {
    // вывести результат
    console.log( xhr.responseText ); // responseText -- текст ответа.
}

XMLHttpRequest usage

function getJSON(url) {
    var xhr = new XMLHttpRequest();

    xhr.open('GET', url);

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.responseText);
            console.log(typeof xhr.responseText);
            console.log(JSON.parse(xhr.responseText));
        }
    };

    xhr.send();
}

XMLHttpRequest event handler

  • 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 event handler

function getJSON(url, successHandler, errorHandler) {
    var xhr = new XMLHttpRequest();

    xhr.open('GET', url);

    xhr.onreadystatechange = function() {
        var status;
        var data;

        if (xhr.readyState === 4) { // `DONE`
            status = xhr.status;

            if (status === 200) {
                data = JSON.parse(xhr.responseText);

                successHandler && successHandler(data);
            } else {
                errorHandler && errorHandler(status);
            }
        }
    };

    xhr.send();
}

getJSON('data.json', function(data) {
    console.log('Success ', data);
}, function(status) {
    console.log('Something went wrong.', status);
});

AJAX for all browsers

 var xhr = typeof XMLHttpRequest !== 'undefined'
        ? new XMLHttpRequest()
        : new ActiveXObject('Microsoft.XMLHTTP');

xhr.responseType

function getJSON(url, successHandler, errorHandler) {
    var xhr = typeof XMLHttpRequest !== 'undefined'
        ? new XMLHttpRequest()
        : new ActiveXObject('Microsoft.XMLHTTP');

    xhr.open('GET', url);

    // browsers that support this feature automatically handle the JSON.parse()
    xhr.responseType = 'json';

    xhr.onreadystatechange = function() {
        status = xhr.status;

        if (status === 200) {
            data = xhr.response; // JSON

            successHandler && successHandler(data);
        } else {
            errorHandler && errorHandler(status);
        }
    };

    xhr.send();
}

getJSON('data.json', function(data) {
    console.log('Success ', data);
}, function(status) {
    console.log('Something went wrong.', status);
});

xhr.responseType and using with promises

var getJSON = function(url) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();

        xhr.open('get', url, true);

        // browsers that support this feature automatically handle the JSON.parse()
        xhr.responseType = 'json'; // ответ будет в виде обьекта, а не строка

        xhr.onload = function() {
            var status = xhr.status;

            if (status === 200) {
                resolve(xhr.response);
            } else {
                reject(status);
            }
        };
        xhr.send();
    });
};

getJSON('data.json').then(function(data) {
    console.log('Success ', data);
}, function(status) {
    console.log('Something went wrong.', status);
});

xhr.responseType sent POST

xhr.send('lorem=ipsum&name=binny');

Если хотим передавать данные в виде json, необходимо установить заголовок который будет говорить серверу как обработать данные.

xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');

Для обработки ошибок необходимо добавить onerror обработчик.

xhr.onerror = function(e) {
    reject("Error fetching " + url);
};
xhr.onerror = function(e) {
    errorHandler && errorHandler(e);
};

Для случая когда используем Promise:

Для случая когда используем function callback:

xhr.responseType sent POST

var saveJSON = function(url, data) {
        return new Promise(function(resolve, reject) {
            var xhr = new XMLHttpRequest();

            xhr.open('post', url, true);
            xhr.setRequestHeader(
                'Content-type', 'application/json; charset=utf-8'
            );

            xhr.responseType = 'json';

            xhr.onload = function() {
                var status = xhr.status;

                resolve(xhr.response);
            };
            xhr.onerror = function(e) {
                reject("Error fetching " + url);
            };
            xhr.send(data);
        });
    };

xhr.responseType json additional

function getJSON(url, successHandler, errorHandler) {
    var xhr = typeof XMLHttpRequest !== 'undefined'
        ? new XMLHttpRequest()
        : new ActiveXObject('Microsoft.XMLHTTP');
    var responseType = 'responseType' in xhr;
    // or
    // browsers that support this feature automatically handle the JSON.parse()
    // xhr.responseType = 'json';

    xhr.open('GET', url);

    xhr.onreadystatechange = function() {
        ...
    };

    xhr.send();
}

getJSON('data.json', function(data) {
    console.log('Success ', data);
}, function(status) {
    console.log('Something went wrong.', status);
});

SOP & CORS

The 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 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.

<script
  type="application/javascript"
  src="http://server.com/api/users?callback=parseResponse">
</script>
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.

Links

Examples

ajax

By Oleg Rovenskyi