Basic AJAX Example - (AJAX Examples)
AJAX (Asynchronous JavaScript and XML) is a powerful tool that allows web pages to update content without reloading. In this tutorial, we'll create a basic AJAX example and explain the syntax, example, output, explanation, use, important points, and summary of AJAX.
Syntax
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Action after the response is received
}
};
xhttp.open("GET", "FILE_NAME", true);
xhttp.send();
Example
Let's create a basic AJAX example that will display a number on the web page. We will create a separate file called example.txt
that contains a number. The AJAX request will open this file and retrieve the number.
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<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", "example.txt", true);
xhttp.send();
}
</script>
</head>
<body>
<h2>Basic AJAX Example</h2>
<button type="button" onclick="loadDoc()">Click me!</button>
<p id="demo"></p>
</body>
</html>
Explanation
In this example, we created a web page with a button and a paragraph element. On button click, the loadDoc()
function is called, which creates a new XMLHttpRequest object. This object sends an HTTP request to the example.txt
file and retrieves its contents. When the request is complete, the readyState
property of the object is set to 4, and the status
property is set to 200 (indicating success). We then retrieve the text from the example.txt
file (which is stored in the responseText
property of the object) and set the contents of the paragraph to that text.
Use
The AJAX technique is useful for updating content on a web page without reloading the page. This can be used to create dynamic and interactive web pages without disrupting the user experience. AJAX can be used for retrieving information from a server, sending data to a server, and updating a part of a web page.
Important Points
- AJAX requests are asynchronous by default, which means that they will not block the execution of the rest of the script.
- AJAX technology allows the page to update content without reloading, thereby improving the user experience.
- AJAX is used to perform asynchronous operations on a server.
- AJAX technology can be used to create a variety of web applications, such as web mail, Google Maps, and many others.
Summary
In this tutorial, we created a basic AJAX example to demonstrate how AJAX works. We discussed the syntax, example, output, explanation, use, important points, and summary of AJAX. With this knowledge, you can begin to create dynamic and interactive web pages using AJAX technology.