Ander Gonzalez Ander Gonzalez - 9 months ago 70
Ajax Question

How to read a value from a website using ajax?

I´m new on JavaScript and I'm trying to do a small project for my website and I need some help.

I need to read the number of players that there are in my server from this website (https://use.gameapis.net/mc/query/players/147.135.204.52) and them write in a my website.

I try this but it dosent work, can you see the problem?



<script>
$(document).on("ready", function() {
setInterval(queryJugadores, 5000);
queryJugadores();
$(".navbar-brand").tooltip({placement: "bottom", html: true});
$("[data-toggle='tooltip']").tooltip();
});

function queryJugadores() {
$.ajax({
url: "https://use.gameapis.net/mc/query/players/147.135.204.52",
method: "GET",
success: function(res){
if (res["status"]) {
actualizarJugadores(res["players"]["online"]);
}
}
});
}

function actualizarJugadores(num) {
var digitos = ("" + num).split("");
var elem = $(".cuenta-jugadores").children("dd");
elem.empty();
for (index = 0; index < digitos.length; index++){
elem.append("<span>" + digitos[index] + "</span>")
}
var color = "#43DBE7";

if (num==0) {
color = "#d9534f"
}
elem.children("span").css("background-color",color);
}

<html>
<body>
<dl class="cuenta-jugadores">
<dd>
<span>0</span>
<span>1</span>
<span>2</span>
<span>3</span>
</dd>
</dl>
</body>
</html>





Many Thanks.

Answer Source

Your code works just fine.

You had some extra code at the top that looks like it needs the jQueryUI library https://jqueryui.com/tooltip/ and refers to elements ( navbar-brand ) that you haven't included in your html. I removed that code.

  $(document).on("ready", function() {
    setInterval(queryJugadores, 5000);
    queryJugadores();
  });

function queryJugadores() {
  $.ajax({
    url: "https://use.gameapis.net/mc/query/players/147.135.204.52",
    method: "GET",
    success: function(res) {
      if (res["status"]) {
        actualizarJugadores(res["players"]["online"]);
      }
    }
  });
}

function actualizarJugadores(num) {
  var digitos = ("" + num).split("");
  var elem = $(".cuenta-jugadores").children("dd");
  elem.empty();
  for (index = 0; index < digitos.length; index++) {
    elem.append("<span>" + digitos[index] + "</span>")
  }
  var color = "#43DBE7";

  if (num == 0) {
    color = "#d9534f"
  }
  elem.children("span").css("background-color", color);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<html>

<body>
  <dl class="cuenta-jugadores">
    <dd>
      <span>0</span>
      <span>1</span>
      <span>2</span>
      <span>3</span>
    </dd>
  </dl>
</body>

</html>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download