Request

Next ❯Ajax Request

We have two ways to do data exchange, asynchronous or synchronous

  • We mostly prefer asynchronous request
    asynchronous : Executes other scripts while waiting for server response
    synchronous : Wait for server response then after execute other scripts

open() (for setup) & send() (for sending request to server) methods must required for the request



Asynchronous Request

Set 'acyn' parameter to 'true' for Asynchronous in open()

open(method, url, true);
  • 'onreadystatechange' property must be required

ajax_demo.txt file used in below examples
<p>AJAX full form is Asynchronous JavaScript and XML</p>
<p className="abc">Hope You enjoy using AJAX</p>
Example: To send request using GET method
<!DOCTYPE html>
<html>
<body>
  <div id="text1"></div>
  <button onclick="fun()">Load (ajax_demo.txt)</button>
<script>
function fun(){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if(this.readyState == 4 && this.status == 200) {
      // here, handle the server response
      document.getElementById("text1").innerHTML = this.responseText;
    }
  };
  xhr.open("GET", "ajax_demo.txt", true);
  xhr.send();
}
</script>
<body>
<html>
OUTPUT:
Sample: To send data with request, using GET method
xhr.open("GET", "ajax_demo.php?x=12", true);
xhr.send();
Sample: To send data with request, using POST method
xhr.open("POST", "ajax_demo.php", true);
xhr.send("x=12");
Sample: To set any specific header while sending the request & it must be called before send()
xhr.open("POST", "ajax_demo.php", true);
// To set header, for more use it again
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xhr.send("x=12&y=13");
  • Note! It doesn't matter what backed language you are using to handle the request, If you are sending any data to the server, then you can handle them on your respective server side, by the same way you handle your normal data variables
  • Note! If you want to stop the current request, then call "xhr.abort()"


Synchronous Request

Set 'acyn' parameter to 'false' for synchronous in open(), use only if required

open(method, url, false);
Example: To send request using GET method
var xhr = new XMLHttpRequest();
xhr.open("GET", "ajax_demo.txt", false);
xhr.send();
// here, handle the server response
document.getElementById("text1").innerHTML = xhr.responseText;

  • Ajax Request
❮ Prev XMLHttpRequest
Next ❯Ajax Request
TryOut Examples"Learn to Explore..!"

TryOut Editor

receipt