ajax programming language code example
Example 1: ajax
With Ajax, web applications can send and retrieve data from a server asynchronously without interfering with the display and behaviour of the existing page.
Example 2: ajax programming
var xhr = new XMLHttpRequest();
xhr.open('GET', 'send-ajax-data.php');
xhr.onreadystatechange = function () {
var DONE = 4;
var OK = 200;
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
console.log(xhr.responseText);
} else {
console.log('Error: ' + xhr.status);
}
}
};
xhr.send(null);
<?php
header('Content-Type: text/plain');
echo "This is the output."; ?>
fetch('send-ajax-data.php')
.then(data => console.log(data))
.catch (error => console.log('Error:' + error));
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();