ajax in programming code example

Example: ajax programming

// BEGIN
// JavaScript example
// An example of a simple Ajax request using the GET method, written in JavaScript.

// get-ajax-data.js:

// This is the client-side script.
// Initialize the HTTP request.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'send-ajax-data.php');

// Track the state changes of the request.
xhr.onreadystatechange = function () {
	var DONE = 4; // readyState 4 means the request is done.
	var OK = 200; // status 200 is a successful return.
	if (xhr.readyState === DONE) {
		if (xhr.status === OK) {
			console.log(xhr.responseText); // 'This is the output.'
		} else {
			console.log('Error: ' + xhr.status); // An error occurred during the request.
		}
	}
};

// Send the request to send-ajax-data.php
xhr.send(null);
// END

// BEGIN
// send-ajax-data.php:
<?php
// This is the server-side script.
// Set the content type.
header('Content-Type: text/plain');

// Send the data back.
echo "This is the output."; ?>
// END 
  
// BEGIN  
// Fetch is a new native JavaScript API  
fetch('send-ajax-data.php')
    .then(data => console.log(data))
    .catch (error => console.log('Error:' + error));
// END

// BEGIN
// ES7 async/await example:  
async function doAjax() {
    try {
        const res = await fetch('send-ajax-data.php');
        const data = await res.text();
        console.log(data);
    } catch (error) {
        console.log('Error:' + error);
    }
}

doAjax();
// END