-1

I have this code:

    var temp = getLevel(0);
    console.log("outside" + temp + "/outside");

    function getLevel(level) {
        var httpRequest, lvlCode;
        if (window.XMLHttpRequest) httpRequest = new XMLHttpRequest(); // most browsers
        if (window.ActiveXObject) httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); // IE8 and older
        httpRequest.open('GET', 'get-level.php', true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === 4) {
                lvlCode = httpRequest.responseText;
                console.log("inside" + lvlCode + "/inside");
                return lvlCode; 
            }
        };
        httpRequest.send("lvl=" + level);
    }

Console returns:

outsideundefinedoutside (index):111
inside<data I want>
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
/inside 

There are two issues here: first, Hosting24 pollutes my echoed data. How do I get rid of the Hosting24 text? Second, why is temp undefined when it should contain exactly the same as lvlCode?

user3324865
  • 163
  • 1
  • 2
  • 10

1 Answers1

2

How do I get rid of the Hosting24 text?

You'd have to parse it out manually. (Or, as mentioned in a comment on the question, use a host which doesn't inject content into your site.) String parsing can often be an inexact science. You might start with something simple like this, or something more complex like regular expressions. (Though HTML parsing with regular expressions is also a very inexact science.)


Second, why is temp undefined when it should contain exactly the same as lvlCode?

The question linked in a comment says it all. (It's kind of a half-duplicate, since you're asking two questions.) Essentially, look at what you're doing:

var temp = getLevel(0);

However, the getLevel function doesn't return anything. Since nothing is returned, naturally temp is going to be undefined. An entirely different function, used as an anonymous callback function to the asynchronous AJAX call, returns something. But where does that return value go? getLevel() finishes executing and returns nothing long before that AJAX call completes. (Hence, "asynchronous")

You don't want to return values from asynchronous callback functions. Instead, you want to perform your actions in response to those callbacks.

So instead of this:

var temp = getLevel(0);
console.log("outside" + temp + "/outside");

function getLevel(level) {
    //...
    httpRequest.onreadystatechange = function() {
        //...
        return lvlCode;
    }
    //...
}

Do this:

getLevel(0);

function getLevel(level) {
    //...
    httpRequest.onreadystatechange = function() {
        //...
        console.log("outside" + temp + "/outside");
    }
    //...
}
Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279