Search code examples
javascriptxmlhttprequest

What does XMLHttpRequest do in that code


I'm a beginner in Javascript , and I want to understand what the method XMLHttpRequest does.

This is the code that I was reading, and I was wondering if someone could explain what it is doing:

var xhttp;
xhttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();

Solution

  • Hi I am not really good in explanations, but I will try to explain this in details as I see and understand this.

    The XMLHttpRequest is an object. It is used for exchanging of data with a server. So with its use you can send some data to the script on the server(request) and get some data back from it(response). That response data can be displayed instantly on the page without page reloading. So this process call AJAX.

    I would read your provided code as

    //define a variable 
    var xhttp;
    /*assign a XMLHttpRequest object to this variable
    check if the global object window has a XMLHttpRequest object already
    if not and user have a newer browser, create one (new XMLHttpRequest - for           IE7+, Firefox, Chrome, Opera, Safari browsers) or user have an older browser (ActiveXObject("Microsoft.XMLHTTP") - for IE6, IE5 browsers)
    xhttp.open method specifies the type of request(method GET, Script on server,    asynchronous)
    xhttp.send method sends the request to a server*/
    
    xhttp=window.XMLHttpRequest?new XMLHttpRequest:new     ActiveXObject("Microsoft.XMLHTTP"),xhttp.open("GET","script.php",!0),xhttp.send();
    

    But you have to check the readyState property of the XMLHttpRequest object as well

    xmlhttp.onreadystatechange = function() {
        //4: request finished and response is ready
        //200: "OK"
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    
            //display of returned data from the server
            //it is available in this property - xmlhttp.responseText
        }
    }
    

    The whole peace of code should look like:

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();                     // code for IE7+, Firefox, Chrome, Opera, Safari
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");   // code for IE6, IE5
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    
            //display of returned data from the server
            //jquery example
            $('div').html(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", "script.php", true);
    xmlhttp.send();
    

    Hopefully this helped, good luck!