Programming Tutorials

A complete sample program in AJAX

By: Ram Baskar in Ajax Tutorials on 2022-11-28  

Here is a simple AJAX example with a HTTP GET request:

<!DOCTYPE html>
	<title>AJAX Example</title>
		function makeRequest() {
			var httpRequest = new XMLHttpRequest();
			httpRequest.onreadystatechange = function() {
				if (httpRequest.readyState === XMLHttpRequest.DONE) {
					if (httpRequest.status === 200) {
						document.getElementById('response').innerHTML = httpRequest.responseText;
					} else {
						alert('There was a problem with the request.');
			};'GET', '');
	<h1>AJAX Example</h1>
	<button onclick="makeRequest()">Make Request</button>
	<div id="response"></div>

In this example, we have a button on the web page that when clicked, it calls the makeRequest() function. This function creates a new XMLHttpRequest object and sets a callback function to handle the server response. It then opens a GET request to the specified URL and sends the request. Once the server responds, the callback function is called to handle the response. In this example, we simply display the response in a div on the web page. If there is a problem with the request or the server responds with a non-200 status code, we display an error message in an alert box.

Note that in this example, we are making a request to a JSON API endpoint and displaying the response on the web page. However, this example can be adapted to work with any type of HTTP request and response.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Ajax )

Latest Articles (in Ajax)