Popular Tags

[Snippets] Pure JS AJAX Request

programix · ·

Simple GET request

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var xmlHttp = new XMLHttpRequest();

//define request
xmlHttp.open("get", "url", true); 
//send request
xmlHttp.send();

//handle response
xmlHttp.onreadystatechange = function()
 {
  //check if successful response
  if(xmlHttp.readyState === 4 && xmlHttp.status === 200)
  {
   console.log(xmlHttp.responseText);
  }
 } 

We started this simple snippet with XMLHttpRequest() constructor call. This object is defined in Javascript Built-in Library and supported in all current browsers.

Function "onreadystatechange" is triggered when a response comes from the server.

In the example above we determine if the response is successful. The "readyState" variable returns 4 if the operation is complete.

For "real" application also check other possible outcomes. We are also checking response code("status" variable) for 200 which is standard code for successful response. Similar to "readyState" you should check response codes.

Most commonly you will get 404 Not Found, 500 Internal Server Error or some kind of redirect like 301 or 302. Handle these statuses properly.



Asynchronous or Synchronous AJAX request

In function "open" you can define if request should by sync (false) or async(true). A sync request wait for the server to response, which can be dangerous if the server is slow because it stop executing Javascript. It is recommended to use async and deal will response when it is ready.

XMLHttpRequest POST, PUT, PATCH, DELETE

If POST, PUT, PATCH or DELETE is needed than just change "get" to your needed HTTP method.

Javascript HTTP Ajax Request explained with XMLHttpRequest
Ajax Request


Pinned Post
[Snippets] Pure JS AJAX Request
Simple GET request 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 var xmlHttp = new XMLHttpRequest(); //define request xmlHttp...