R__
R__

Reputation: 183

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?

Upvotes: 0

Views: 4886

Answers (1)

Marc
Marc

Reputation: 1430

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 );
})();

Upvotes: 2

Related Questions