There are many ways to call Ajax in JavaScript for submitting data to the server, checking username, creating a chat room, autocomplete form, vote or rate the product.
XMLHttpRequest object
Code example:
<script type="text/javascript">
function loadXMLDoc() {
var myxmlhttp = new XMLHttpRequest();
myxmlhttp.onreadystatechange = function() {
if (myxmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (myxmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = myxmlhttp.responseText;
}
else if (myxmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
myxmlhttp.open("GET", "ajax_info.txt", true);
myxmlhttp.send();
}
</script>
Fetch API
It is easy and flexible, supports modern browsers, follows a request-response model.
Code example:
fetch("myData/user_repo.json").then(function(response){
console.log(response);
});
jQuery – It is a client-side JavaScript library
Code example:
$.ajax({ url: "test.html", context: document.body, success: function(){
$(this).addClass("done");
}
});