AJAX in JavaScript with JSON

Receiving data from server

var btn = document.getElementById('btn');
btn.addEventListener("click", function() {
 var ourRequest = new XMLHttpRequest();
 ourRequest.open('GET', put_url_here);
 ourRequest.onload = function() {
  if(ourRequest.status >= 200 && ourRequest.status < 400) {
   var ourData = JSON.parse(ourRequest.responseText);
   userDefinedFunction(ourData);
  } else {
   console.log('Error from server side. Either server send error or wrong data formta');
  }
 };
 ourRequest.onerror = function() {
  console.log("Error for connection. Maybe the connection of client has disrupted");
 };
 ourRequest.send();
});

Labels: ,

© copyright-2020 Rejaul