What is: AJAX

AJAX (Asynchronous JavaScript and XML) is a JavaScript method to exchange information with a server in the background and update a portion of the website without refreshing the whole page in the browser. For example, when you post something on Facebook or when you chat in Messenger, that happens with the AJAX method as well.

Here is a quick code example:

<div id="demo" onclick="ajaxLoad()">Click on this text to change content!</div>

<script type="text/javascript">
function ajaxLoad(){
    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (this.readyState == XMLHttpRequest.DONE){
            if (this.status == 200) {
               document.getElementById('demo').innerHTML = this.responseText;
            }else if (this.status == 400) {
               alert('There was an error 400!');
            }else {
                alert('Something else other than 200 was returned!');
            }
        }
    };

    xhttp.open('GET', 'https://yoursite.com/api', true);
    xhttp.send();
}
</script>

Note: if you will make a request to a different domain than yours, it could block your request. In this case you’ll see an error message in your browser console, something like this: “Cross-Origin Request Blocked”. You can read more about this here.

For more information about AJAX visit Mozilla’s developer guide.

 

 

Recent articles

loading
×