DEV Community

Kauress
Kauress

Posted on • Updated on

Ajax and toast

AJAX on toast
My notes on AJAX. Nothing less, nothing more. Why toast? Because.

--------/----------
work in progress
----------/--------

Introduction

  1. AJAX stands for async JS and XML.
  2. Assists in communicating with a browser [receiving and sending data] after a page has loaded.
  3. Remains a popular method of communicating with a server from the front end .
  4. It enables the sending of data to the server, and receiving a response without the page reloading (think facebook feeds).
  5. Fundamental to this async communication is the XMLHttpRequest object originally released by Microsoft in 1999

Asyncrhonous

  1. Async code works like this:
    • Request made
    • JS engine moves on to the next task before a response is received
    • Rest of the script is executed
    • That means the webpage does not freeze while waiting for a response

XMLHttpRequest object

  1. Working with async requests and responses revolves around using the XMLHttpRequest object.
  2. This is a native object provided by the browser.
  3. So the properties and methods of this object are what we use to communicate with the browser.

Browser support

1.XMLHttpRequest 1.0 specification is supported in all mainstream browsers.

  1. The newer XHR 2.0, is also very well supported with some exceptions (Opera mini and IE11).

Same origin policy

  1. When making AJAX requests to servers, we can only receive responses from a server from the same domain that we make a request to.

The XMLHttpRequest Constructor

1.The XMLHttpRequest Constructor is used in order to create a XMLHttpRequest object which will in turn allow us to make AJAX requests and receive responses.

var xhr = new XMLHttpRequest();
  1. var xhr now contains an instance of the XMLHttpRequest.
  2. The 'xhr' object has different methods, properties and states.
  3. A newly created 'xhr' object is in an unsent state.

xhr [XMLHttpRequest] object states

State Numeric Value Explanation
UNSENT 0 Newly created XMLHttpRequest Object
OPENED 1 This means that the "open" method has been invoked on the object to open a connection to the server
HEADERS_RECEIVED 2 HTTP headers of the response have been received and redirects followed
LOADING 3 The body of the response is loading
DONE 4 the response has been fully received or failed

Event handler for the XMLHttpRequest object

  1. The readyState property of the XMLHttpRequest object holds the state of the object (0,1,2,3 or 4).
  2. The onreadystatechange property defines a function which will run when the state changes.
  3. The onreadystatechange event handler (like "onclick") is an 'on-event' handler. They are usually added to DOM elements such as buttons and input elements to detect changes such as a click or keypresses. But they can also be used on XMLHttpRequest objects.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    // handle readystatechange event
};
  1. Inside the event handler's function we can check the readyState property of the object
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        // do something with the response
    }
};
  1. A change in the readyState property will cause the event handler to be invoked.
  2. The readyState property is updated with the number that represents the current state of the object.

XMLHttpRequest 2.0 Event Handlers

  1. Version 2.0 uses the onload event that will only load once the request succeeds.
  2. A function is assigned to the onload property of the 'xhr' object.
  3. The readyState property need not be checked.
xhr.onload = function() {

}

### Other XMLHttpRequest 2.0 Event Handlers

Event Numeric Value
onabort Aborted request
onerror Failed request
onload Successful request
onloadend Request has finished
onloadstart Request has started
onprogress Request is transmitting data
ontimeout Request time has elapsed

Connecting to a server

  1. Initializing/opening a connection with a server is done with the 'open' method.
  2. The 'open' method takes 2 arguments:
    • A GET or POST request to either retrieve/GET data from a server or send/POST data to a server
    • The resource that we want to GET or POST to.
xhr.open('GET', '/response.json');

Sending a request to a server

  1. After a connection has been opened by the 'open' method, data can be sent to the server with the 'send' method.
xhr.send();
  1. The 'send' method can take in the following types of data as an argument:
    • FormData
    • Blob
    • Document
    • DOMString
    • ArrayBufferView

Handling responses

  1. The 'xhr' object's properties are updated once a request is successful.
  2. Usually the 'response' property is updated when using the 'onload' event event handler [ or the responseText property if using the onReadyStateChange event handler]. 3.The data sent back from the server once the onload event is triggered, is available to the response property of the 'xhr' object.
  3. Response propertt: contains data returned by the server
  4. The 'status' property contains the numerical HTTP response code
xhr.onload = function () {
    /* do something with the response 
    if the status property of the 'xhr' object is === 200
    use JSON's parse method to parse the JSON string into a JS object 
    then get the contents using .data */
    if (xhr.status === 200) {
        console.log(JSON.parse(xhr.response).data);
    }
};

Working with forms

  1. For SPA's [Single Page Applications] sending form data without re-loading the page provides for better UX.
  2. Form data is sent using the FormData object.
  3. A new formData object is created by using the FormData constructor.
  4. A submit event can be used to trigger the creation of a new XMLHttpRequest.
  5. The 'append' method is used to add data to the formData object. 6.
var form = document.getElementById('login');
form.addEventListener('submit', function (event) {
var xhr = new XMLHttpRequest(),
formData = new FormData();
formData.append('username', document.getElementById('username').value);
formData.append('password', document.getElementById('password').value);
xhr.open('POST', '/signin');
xhr.send(formData);
event.preventDefault();    
});

Uploads

  1. The upload property of the 'xhr' object allows you to track the progress of uploads

Discussion (0)