Connor S Connor S - 20 days ago 5
HTML Question

Can't get response using JSON API

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>

Answer

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>