AJAX Introduction

AJAX is the very useful in the development because by using ajax a developer can:

  • Read data from a web server – after the page has loaded
  • Update a web page without reloading or refreshing the page
  • Send data to a web server – in the background(fire the request in background)

What is AJAX?

AJAX stands for = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX just uses a combination of:

  • A browser built-in XMLHttpRequest object (to request the data from a web server in background)
  • JavaScript and HTML DOM (to display or use the data received from the server request)

How AJAX Works

1.  When an event occurs in a web page (the page is loaded, a button is clicked)

2. JavaScript  create an XMLHttpRequest object

3. The above XMLHttpRequest object sends a request to a web server

4. The server get the request and processed accordingly

5. The server sends the response back to the web page(to client)

6. The response is read by JavaScript

7. Proper action (like page update) is performed by JavaScript

Input:-
<!DOCTYPE html>
<html>
<body>

<h2>The Example for XMLHttpRequest Object</h2>

<p id="result">AJAX will change this text.</p>

<button type="button" onclick="loadFileContent()">Change Content</button>

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

</body>
</html>

Output (Before click):-

Output (After click):-