Search code examples
javascriptgoogle-chrome-extensionxmlhttprequest

Send HTTP request using JavaScript?


I'm trying to get a JSON object from http://api.roblox.com/marketplace/productinfo?assetId=361192737 (link) using a GET request, but it doesn't seem to be working.

(function(){
    var xmlHttp;
    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", 'http://api.roblox.com/marketplace/productinfo?assetId=361192737', true );
    xmlHttp.send( null );
    function ProcessRequest(){
        console.log(xmlHttp.responseText); // "" (empty string)
        var respData = JSON.parse(xmlHttp.responseText) || {};
        RemoteEvents = JSON.parse(respData.Description) || null;
    }
})()

This is on a Chrome Extension in Development Mode. I'm not very experienced with JavaScript, and even less with HTTP requests. What am I doing wrong?


Solution

  • The callback " onreadystatechange " will be called multiple times with different " state codes ". You have to check the code before trying to get the data to be sure that the request ended. The code value when it finished is 4, have a look here : http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

    This should work :

    (function(){
        var xmlHttp;
        xmlHttp = new XMLHttpRequest(); 
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                console.log(xmlHttp.responseText); // "" (empty string)
                var respData = JSON.parse(xmlHttp.responseText) || {};
                RemoteEvents = JSON.parse(respData.Description) || null;
            }
        };
        xmlHttp.open( "GET", 'http://api.roblox.com/marketplace/productinfo?assetId=361192737', true );
        xmlHttp.send( null );
    })();