0

I was wondering what I was doing wrong with this code? I'm trying to get the response for PC players from the API to be set to a

tag in the html, but this isn't working. Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Battlefield 4 Tracker</title>

    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/jquery-3.1.1.min.js"></script>
</head>
<body>

<div id="fullscreen">
    <div class="fullscreen-content">
        <div id="centered">
            <h1>Battlefield 4 Stats Tracker</h1>
            <input id="username" name="username" placeholder="PSN Username">
            <button id="submit">Submit</button>
            <p id="response">
                Response goes here.
            </p>
        </div>
    </div>
</div>

<script>
    var request = new XMLHttpRequest();

    var jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)

    var obj = JSON.parse(jsonResponse);

    document.getElementById("response").innerHTML = obj.pc[1].count + "";
</script>

</body>
</html>
Andreas
  • 21,535
  • 7
  • 47
  • 56
Connor S
  • 39
  • 1
  • 1
  • 3
  • 1
    Did you try running your code in the snippet? It returns an error. – junkfoodjunkie Nov 19 '16 at 15:54
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Nov 19 '16 at 16:01

5 Answers5

1

Since you are using JQuery as suggested by the html you provided , you can use $.get method of it. This method is a simple wrapper to work with the xmlHTTP asynchronous calls. The success call back of this method is where you should populate the obj with response.

And obj.pc is also an object, so you should access it like obj.pc.count

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Battlefield 4 Tracker</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>

</head>
<body>

<div id="fullscreen">
    <div class="fullscreen-content">
        <div id="centered">
            <h1>Battlefield 4 Stats Tracker</h1>
            <input id="username" name="username" placeholder="PSN Username">
            <button id="submit">Submit</button>
            <p id="response">
                Response goes here.
            </p>
        </div>
    </div>
</div>

<script>
    var request = new XMLHttpRequest();
    var obj = null;
     var jsonResponse = $.get("http://api.bf4stats.com/api/onlinePlayers", function(response){   
      obj = response;       
      document.getElementById("response").innerHTML = obj.pc.count + "";
    })



</script>

</body>
</html>
Deep
  • 9,594
  • 2
  • 21
  • 33
0

you forgot to send the XMLHttpRequest and what you get back is a object of object so you can call directly obj.pc.count. Try this one:

var json = new XMLHttpRequest();

json.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
json.send(null)

var obj = JSON.parse(json.responseText);

document.getElementById("response").innerHTML = obj.pc.count;
Lucas Jahn
  • 306
  • 1
  • 3
  • 14
0
  • The request is never send send();
  • The correct way to do this is to handle it in the onreadystatechange event.

Try this (together with a proper check):

var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";

xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
        var obj = JSON.parse(this.responseText);
        myFunction(obj);
    }
};

xmlhttp.open("GET", url, true);
xmlhttp.send();


function myFunction(obj) {        
    document.getElementById("response").innerHTML = obj.pc.count;
}

or directly without extra function:

var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";

xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
        var obj = JSON.parse(this.responseText);
        document.getElementById("response").innerHTML = obj.pc.count;
    }
};

xmlhttp.open("GET", url, true);
xmlhttp.send();

Demo

var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";

xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
        var obj = JSON.parse(this.responseText);
        document.getElementById("response").innerHTML = obj.pc.count;
    }
};

xmlhttp.open("GET", url, true);
xmlhttp.send();
<div id="response"></div>
Jim
  • 2,974
  • 2
  • 19
  • 29
0

You never sent the request. You're missing request.send(). You then listen for the load event, when you've gotten a response.

Here's an edited version of your code. I assumed that you want to loop through all the types of devices and count them.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="fullscreen">
    <div class="fullscreen-content">
        <div id="centered">
            <h1>Battlefield 4 Stats Tracker</h1>
            <input id="username" name="username" placeholder="PSN Username">
            <button id="submit">Submit</button>
            <p id="response">
                Response goes here.
            </p>
        </div>
    </div>
</div>

<script>
function reqListener () {
  //THIS HAPPENS AFTER THE REQUEST HAS BEEN LOADED.
  var obj = JSON.parse(this.responseText);
  var counter = 0; 
  for(var k in obj) {
    var o = obj[k];
    counter += o.count;
  }
  document.getElementById("response").innerHTML = counter;
}

var request = new XMLHttpRequest();
request.addEventListener("load", reqListener);
request.open("GET", "http://api.bf4stats.com/api/onlinePlayers");
request.send();
  
</script>

</body>
</html>

You may want to consider other events such as a failed attempt to load the request, etc. Here's more info: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Victoria Ruiz
  • 4,913
  • 3
  • 23
  • 40
-1

Try this one :-

<script>
    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var obj = JSON.parse(this.responseText);
            document.getElementById("response").innerHTML = obj.pc.count + "";
        }
    };
    jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", true);
    request.send();
</script>
Sachin Kumar
  • 3,001
  • 1
  • 22
  • 47