Asynchronous JavaScript and XML

A basic use case for AJAX is to read files using JavaScript

let's see how that works

Step #1

Create a request object

var myRequest = new XMLHttpRequest()

myRequest is now an object containing methods for fetching data from a file

Step #2

Deciding the type of data to expect

myRequest.responseType = "text"

Possible response types:

"arraybuffer" An immutable array of binary raw data
"blob" A file as an object with raw data
"document" If the requested files is an SVG, HTML or XML file you'll get a DOM object back.
"json" If the requested file contains a json string you will get a parsed object back
"text" (default) Whatever document you request, you get the result as a string.

Step #3

Initialising the request

var method = "GET"; 
var url = "footer.html";
myRequest.open(method, url);

This is where you decide which file you want to read.

 

Normally, you can only get files from the server we do the request from.

 

Some servers provide support for CORS which tells your browser that it's ok and safe to get this file.

Step #4

Sending the request

myRequest.send();

This is where the request is sent. 

 

Since the default setting is to make an asynchronous request,

meaning we don't know how long it's going to take,

we now have to wait for the response...

Step #5

Waiting for the response

myRequest.addEventListener("load",dealWithResponse);

As soon as the requested document has arrived,

the "load" event will fire and your function
(dealWithResponse) will be called.

Step #6

Dealing with the response

myRequest.addEventListener("load",dealWithResponse);

function dealWithResponse(){
    document.body.innerHTML = myRequest.response;
}

myRequest.response will contain your requested data

in the format you decided on in step #2

 

In this case we chose text and we requested an html document
the result will be the html code from that document as a string.

Requesting data from a public API that support CORS

List of Public API's

(Some may not have CORS support)

Ajax

By Johan Kohlin

Ajax

  • 771