ajax development code example
Example 1: how to make ajax request javascript
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<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", "demo_get.asp", true);
xhttp.send();
}
</script>
</body>
</html>
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();