llw
llw

Reputation: 201

Automatically update with AJAX

I'm currently using this code on my webpage:

<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));

if (!empty($data->invasions)) {
    echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
    $i = 0;
    foreach($data->invasions as $title => $inv) {
        print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}

            </h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}

            </h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}

            </h3>";

        if (count(($data->invasions) > 1)) {

            if (end($data->invasions) !== $inv) {
                print "<hr>";
            } else {
                print "<br style='font-size:2px;'>";
            }

        }

    }

} else {
    echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}

?>

I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!

Upvotes: 1

Views: 4285

Answers (3)

StackSlave
StackSlave

Reputation: 10627

Your problem is a failure to understand AJAX. Below is a $.post() example.

First let's make the page that you want your Client (the Browser user) to see:

viewed.php

<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <style type='text/css'>
      @import 'whatever.css';
    </style>
    <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
    <script type='text/javascript' src='whatever.js'></script>
  </head>
<body>
  <div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>

Now you need your JavaScript in whatever.js.

$(function(){
function getData(){
  $.post('whatever.php', function(data){
    // var htm = do a bunch of stuff with the data Object, creating HTML
    $('#output').html(htm);
  });
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});

On whatever.php:

<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>

The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:

$.post('whatever.php', function(data){

Upvotes: 1

shampoo
shampoo

Reputation: 1281

You can simply reload the page with the method proposed here

But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to

  1. Almost forget your PHP code
  2. use the following code to implement the request to the url

    $.ajax({ url: "https://www.toontownrewritten.com/api/invasions", }) .done(function( data ) { if ( console && console.log ) { console.log( data ); } });

  3. Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.

  4. Put that part of code in a setInterval

    setInterval(function(){ //$.ajax(); }, 10000);

  5. And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .

Upvotes: 5

Arindam Nayak
Arindam Nayak

Reputation: 7462

I have a better suggestion, again it is same as using setInterval.

setInterval(function () {
    if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
    isActive = true;

    try {
        $.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
            isActive = false; // error callback
        });
    } catch (ex) { isActive = false;}
}, 10000);

Upvotes: 1

Related Questions