Server Request Using JavaScript

Do you think how many ways to send or receive data from server using JavaScript?

Most of them know XmlHttpRequest and Fetch can be used for reading or sending data from/to server. Some time webSocket but little bit fear about the implementation. Let’s talk about 5 ways of make a server request from Front-end.

  • XmlHttpRequest API
  • Fetch API
  • Polling
  • WebSocket API
  • Server Sent Events

XmlHttpRequest

This method is the most oldest and reliable way to send or receive any data from/to server.

  • Create instance of XmlHttpRequest
let xhr = new XMLHttpRequest();
  • Initialize it
xhr.open(method, url ,[ async, user, password ])

method – HTTP methods "GET""POST""PUT""DELETE"
url – It could be server IP or DNS and relative path to resource
async : Optional– defaulting to true means all requests are asynchronously
user : Optional – User name to use for authentication purposes
password : Optional – password to use for authentication purposes

  • Send it
xhr.send(body)

body : Optional – It could be any data, JSON, XML, raw data

  • Listen to Events
    1. abort| onabort – fired when a request has been aborted
    2. error | onerror – fired when the request encountered an error
    3. loadstart | onloadstart – fired when  a request has started to load data.
    4. load | onload – fired when the result is ready, that includes HTTP errors like 404.
    5. progress | onprogress – fired periodically when a request receives more data.
xhr.onabort = function() {
  alert(`Request has been canceled`);
};

xhr.onerror = function() {
  alert(`Network Error`);
};

xhr.onloadstart = function() {
  alert(`Data download started`);
};

xhr.onload = function() {
  alert(`Loaded: ${xhr.status} ${xhr.response}`);
};

xhr.onprogress = function(event) { 
  alert(`Received ${event.loaded} of ${event.total}`);
};

Fetch API

Fetch api provides  a more powerful and flexible feature set, however it does not support for old browsers.

let promise = fetch(url, [options])

url – the URL to access
options – optional parameters: method, headers etc

Since Fetch response  provides multiple promise-based methods, so that we can access the body in various formats.

response.text() – read the response and return as text
response.json() – parse the response as JSON
response.formData() – return the response as FormData object
response.blob() – return the response as Blob (binary data with type)
response.arrayBuffer() – return the response as ArrayBuffer (low-level representation of binary data)
response.body is object, it allows to read the body chunk-by-chunk, we’ll see an example later

Also We can easily chain methods.

fetch('url')
  .then(response => response.json())
  .then(data => alert(data));

Polling

Polling is a simple way of making persistence connection with server and There are two type of polling

  1. Regular Polling
  2. Long Polling

Regular Polling

Making Regularly request to ask any message available is call Regular Polling.

setTimeout(function(){
  fetch('url')
  .then(response => response.json())
  .then(data => alert(data));
},10000);

Long Polling

First UI make a request to server and server will not close the connection until server has a message to sent.

In HTTP/1.0 you can add below code in initial request header. Which tells server to do not close connection.

Connection: keep-alive HTTP 1.0

HTTP/1.1 all connections are considered persistent unless declared otherwise. Timeout will be vary base on web server.

HTTP/2.0 has new feature call Request multiplexing, it also similar to this.


WebSocket

The WebSocket makes it possible to open a two-way interactive communication session between the user’s browser and a server. 
It supports bidirectional message send .

There are two protocols use for communicate with server. ws and wss

let socket = new WebSocket("ws://url");

Once a socket is created, There are 4 events to listen.

  • open | onopen– connection established
  • message | onmessage – data received
  • error | onerror – websocket error
  • close | onclose – connection closed
let socket = new WebSocket("wss://url");

socket.onopen = function(e) {
  alert("Connection established");
  socket.send("Hi There"); //Send to server
};

socket.onmessage = function(event) {
  alert(`Data received from server: ${event.data}`);
};

socket.onclose = function(event) {
    alert('Connection closed');
};

socket.onerror = function(error) {
  alert(`Error ${error.message}`);
};

When user in slow network, WebSocket is smart enough to buffer data. We can check how much data pending to send though bufferedAmount, base on that we can send more data to client side.

let socket = new WebSocket("wss://url");

setInterval(function() {
  if (socket.bufferedAmount == 0) {
    socket.send(moreData());
  }
}, 100);

Connection Status

  • 0 – CONNECTING : the connection has not yet been established,
  • 1 – OPEN : communicating,
  • 2 – CLOSING : the connection is closing,
  • 3 – CLOSED : the connection is closed.

Server Sent Events

We know, web page has to initiate request to read data from web server. But in this technique, server will send data to browsers. it only supports plain text messages.

var evtSource = new EventSource(url)
  • Listen to Events
  1. error | onerror – fired when a connection with an event source fails to be opened
  2. message | onmessage – fired when data is received through an event source.
  3. open | onopen – fired when a connection with an event source is opened.
var evtSource = new EventSource('site.php');

evtSource.onerror = function() => {
  console.log("An error occurred while attempting to connect.");
};

evtSource.onmessage = function(event) => {
  console.log(e.data);
};

evtSource.onopen = function() => {
  console.log("The connection has been established.");
};

EventSource is alternative to WebSocket, as it’s more low-level and lacks such built-in features. However, It supports all modern browser expect IE.

Leave a Reply