Ajax

Ajax stands for Asynchronous JavaScript and XML and allows us to send HTTP request to the server without refreshing the page by using XMLHttpRequest Object. Since it is asynchronous, it does not block execution of other javascript code. It is basically just wrapper of XMLHttpRequest so let's take a look how XMLHttpRequet looks like.

XMLHttpRequest

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function(){

  console.log(xhttp.readyState);

  if (xhttp.readyState == 4 && xhttp.status == 200) {
    console.log("status 200")
  }

}

xhttp.open("GET", "./json/data.json", true);
xhttp.send();

XMLHttpRequest#readyState

readyState represents status of connection between the client and the server.

Status code Detail
0 Request not initialized
1 Server connection established
2 request received
3 processing request
4 request finished and response is ready

XMLHttpRequest#setRequestHeader

Configure HTTP header.

xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

XMLHttpRequest#open(method, url, async)

Specifies the type of request
@method String: the type of request: GET or POST
@url String: the file location
@async Boolean: true (asynchronous) or false (synchronous)

XMLHttpRequest#send

Sends a request to the server (used for GET)

XMLHttpReques#send(data)

Sends a request string to the server (used for POST)

  • @data String: data string params

XMLHttpRequest#status

XMLHttpRequest#responseText

XMLHttpRequest#responseXML


What are the advantages and disadvantages of using Ajax?

The advantages are fetching data without refreshing. You can not build a single page application without Ajax - XMLHTTPRequest. User experience will be much better because there is no refreshing page time.

The disadvantages are cross origin policy will be applied and affects to SEO. You have to set up HTTP header to allow access and show data such as access-control-allow-origin. Otherwise, the data will be opaque and able to be consumed by the client.

what-are-the-advantages-and-disadvantages-of-making-ajax-calls-using-jquery


How JSONP works (and how it's not really Ajax).

JSONP does not work like Ajax. JSONP is called from <script> tag without same origin policy since same origin policy is not applied inside <script> tag. When the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:

what-is-jsonp-all-about

results matching ""

    No results matching ""