Ajax refers to asynchronous java script and xml. It is not a not a programming language. Ajax is of Asynchronous type. It normally uses XML, plain text or JSON to communicate with server i.e. for data transfer.
Note: Ajax is technology independent.
Example
<!DOCTYPE html> <html> <body> <h2>AJAX Hello World</h2> <p id="demo">Update content using ajax.</p> <button type="button" onclick="loadDocument()">Update Content</button> <script> function loadDocument() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "test.txt", true); xhttp.send(); } </script> </body> </html> |
Example explanation
We have used here two files AjaxHelloWorld.html and test.txt. Keep these two files in same folder.
- When you open html file in browser. We will be able to see Update Content button.
- When we click Update Content button, it will call loadDocument() method.
- We creates an XMLHttpRequest object which is used for communication between client and server.
- The XMLHttpRequest object invokes open method to open the connection for a request to test.txt file. In open method, we use true for async parameter which means Asynchronous data transfer will be activated.
- The send method will send the request.
- The server processes the request.
- When server sends a response back to the web page, onreadystatechange = function()executes and updates the page content.