Ajax tutorial for beginners

Introduction:

  1. Ajax menas asynchronous javascript and xml.
  2. Ajax is a web development technique for creating interactive web applications.
  3. Ajax mainly used for without loading the entire page to get the response from the server.
  4. Ajax uses HTML CSS and javascript.
  5. Google and Gmail and so.... popular web applications used the ajax.

Ajax follows these steps:

  • Create the XMLHttpRequest object.
  • Send the HTTP request using the req.send method.
  • Process the HTTP request and create the response and send the data back to the server.
  • Process the data using javascript.
  • Update the page with content.
XMLHttpRequest object properties :
onreadystatechange: Function to be called when the readystate property changes.
ready state : 0 Request not initialized.
                    1 Server connection established.
                    2 Request received.
                    3 Process request.
                    4 requests finished and the response is ready.
status code  200 ok
                    403 forbidden
                    404 not found
Ajax follows these steps
  1. Create the XMLHttpRequest object.
  2. Send the HTTP request using the req.send method.
  3. Process the HTTP request and create the response and send the data back to the server.
  4. Process the data using javascript.
  5. Update the page with content.
Ajax Flow

Sample Example:
<!DOCTYPE html>
<html>
    <title>Introduction to Ajax</title>
<body>

<div id="demo">
<h1>Introduction to Ajax</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
</script>

</body>
</html>
ajax_info.txt:

Welcome to Ajax introduction.
Explanation:

  • First, create the XMLHttpRequest object.
  • Send the HTTP request using the req.send method.
  • Send a request to a server, we are using the open() and send() methods of the XMLHttpRequest object.
  • xhttp.open("GET", "url", true); //Get:method type,server url,request asynchronous(true) or synchronous(false)
  • xhttp.send();// sending the request to the server
  • XMLHttpRequest object you can define a function to be executed when the request receives an answer.
Execution

Output