0

I have a fuction request.send(); that parses a .json file, and gets credits by current steamid

var request;
if (window.XMLHttpRequest) {
  request = new XMLHttpRequest();
} else {
  request = new ActiveXObject("Microsoft.XMLHTTP");
}

request.open('GET', './players.json');
request.onreadystatechange = function() {
  if ((request.readyState === 4) && (request.status === 200)) {
    var items = JSON.parse(request.responseText);
    for(var i = 0; i < items.length; i++)
    {
      if(items[i].steamid == currentSteamID)
      {
        playerCredits = parseFloat(items[i].credits);
        alert(playerCredits);
        return playerCredits;
      }
    }
  }
}

var playerCredits = request.send();
alert(playerCredits);

The first alert works fine:

First Alert


I want to use the credits later, that is why I assigned the function to a variable:

var playerCredits = request.send();

But alerting playerCredits give me this:

Second Alert


By searching for similiar questions I found out that I needed to use Callback, I tried doing this:

var request;
if (window.XMLHttpRequest) {
  request = new XMLHttpRequest();
} else {
  request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', './players.json');
request.onreadystatechange = function(callback) {
  if ((request.readyState===4) && (request.status===200)) {
    var items = JSON.parse(request.responseText);
    for(var i = 0; i < items.length; i++)
    {
      if(items[i].steamid == currentSteamID)
      {
        playerCredits = parseFloat(items[i].credits);
        callback(playerCredits);   
      }
   }
 }
}

request.send(function() {
   console.log(playerCredits);
});

However this is the error I get:

Uncaught TypeError: callback is not a function

I'm pretty sure I'm not using Callback as I'm supposed to, and now I ask you:

What needs to be changed for this to work?

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
Admiral Giggles
  • 163
  • 1
  • 8
  • there are many inconsistencies in your code, you seem to be new to JavaScript. I recommend you to lookup for the exact meaning of important keywords such as Callback, XHR. Wikipedia is a good place for that. I could probably answer, but how many times will you stop by again? – Walle Cyril Mar 14 '16 at 01:29

3 Answers3

0

When you write

request.onreadystatechange = ...

what comes after the = is the callback

what comes in those paranteses is maybe an event object but you will find everything you need in your request object. So your callback function doesn't need any parameters.

Having callback(playerCredits); doesn't make any sense whatsoever.

I don't know exactly what you want to do exactly. A callback is a function that is called back after a certain event occurs.

Read this

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Hope this helps

Walle Cyril
  • 3,087
  • 4
  • 23
  • 55
0

Passing a function into the .send function does not pass it into the onreadystatechange function.

You can take advantage of closures by declaring your callback function outside of onreadystatechange.

var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

// Declare the function here
function callback(playerCredits) {
    console.log(playerCredits);
    // Do other awesome stuff here
}

request.open('GET', './players.json');
request.onreadystatechange = function(callback) {
    if ((request.readyState === 4) && (request.status === 200)) {
        var items = JSON.parse(request.responseText);
        for(var i = 0; i < items.length; i++){
            if(items[i].steamid == currentSteamID) {
                var playerCredits = parseFloat(items[i].credits);

                // It is still in scope here.
                callback(playerCredits);   
            }
        }
    }
}

request.send();

Notes:

  • If I were you, I'd instead take advantage of the vast array of JavaScript libraries out there that have already dealt with all of this. I'd look into jQuery if I were you (I have no affiliation with jQuery).

    This is what your code would look like if you used jQuery:

    function callback(playerCredits) {
        console.log(playerCredits);
        // Do other awesome stuff here
    }
    
    $.ajax('./players.json', {
        complete: function(response) {
            var items = JSON.parse(request.responseText);
            for(var i = 0; i < items.length; i++){
                if(items[i].steamid == currentSteamID) {
                    var playerCredits = parseFloat(items[i].credits);
    
                    // It is still in scope here.
                    callback(playerCredits);   
                }
            }
        }
    }
    
  • I used console.log(playerCredits); instead of alert(playerCredits) because it is more versatile. If you console.log an object in most browsers you will see an expansion of the object (rather than [object Object] as you would get from an alert). (See How to open the JavaScript console in different browsers?)

  • I refactored your request declaration with a ternary operator.

  • I declared playerCredits using the var keyword to keep it within function scope of the onreadystate function. Declaring it without using var makes it an automatically global variable.


Further Reading:

Community
  • 1
  • 1
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
0

XMLHttpRequest.onreadystatechange is an event handler, in other words, a function that is called each time an event is invoked, in this case - the state of the request has been changed.

Quoting this answer: What is a callback function?

A callback function is a function which is:

  • passed as an argument to another function, and,
  • is invoked after some kind of event.

They both achieve the same thing, just a difference in how they are passed to the interpreter.

Send function is a void function, and that means it does not return any value. So assigning your send function to a variable means nothing, if you want to use the response got then you have to assign request.responseText to a variable, but only after we got the response, and that means in the event handler.

You might want to look into this: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest .

But you will almost never use the native javascript to send your ajax requests, jQuery is a libary that helps you do these kind of things with ease: http://api.jquery.com/jquery.ajax/ .

Community
  • 1
  • 1
tehabstract
  • 529
  • 6
  • 14