My notes on AJAX. Nothing less, nothing more. Why toast? Because.
--------/----------
work in progress
----------/--------
Introduction
- AJAX stands for async JS and XML.
- Assists in communicating with a browser [receiving and sending data] after a page has loaded.
- Remains a popular method of communicating with a server from the front end .
- It enables the sending of data to the server, and receiving a response without the page reloading (think facebook feeds).
- Fundamental to this async communication is the XMLHttpRequest object originally released by Microsoft in 1999
Asyncrhonous
- 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
- Working with async requests and responses revolves around using the XMLHttpRequest object.
- This is a native object provided by the browser.
- 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.
- The newer XHR 2.0, is also very well supported with some exceptions (Opera mini and IE11).
Same origin policy
- 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();
- var xhr now contains an instance of the XMLHttpRequest.
- The 'xhr' object has different methods, properties and states.
- 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
- The readyState property of the XMLHttpRequest object holds the state of the object (0,1,2,3 or 4).
- The onreadystatechange property defines a function which will run when the state changes.
- 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
};
- 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
}
};
- A change in the readyState property will cause the event handler to be invoked.
- The readyState property is updated with the number that represents the current state of the object.
XMLHttpRequest 2.0 Event Handlers
- Version 2.0 uses the onload event that will only load once the request succeeds.
- A function is assigned to the onload property of the 'xhr' object.
- 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
- Initializing/opening a connection with a server is done with the 'open' method.
- 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
- After a connection has been opened by the 'open' method, data can be sent to the server with the 'send' method.
xhr.send();
- The 'send' method can take in the following types of data as an argument:
- FormData
- Blob
- Document
- DOMString
- ArrayBufferView
Handling responses
- The 'xhr' object's properties are updated once a request is successful.
- 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.
- Response propertt: contains data returned by the server
- 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
- For SPA's [Single Page Applications] sending form data without re-loading the page provides for better UX.
- Form data is sent using the FormData object.
- A new formData object is created by using the FormData constructor.
- A submit event can be used to trigger the creation of a new XMLHttpRequest.
- 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
- The upload property of the 'xhr' object allows you to track the progress of uploads
Top comments (0)