1

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!

Emobe
  • 660
  • 11
  • 32
llw
  • 201
  • 1
  • 3
  • 15
  • why not using `setinterval`? – shampoo Oct 07 '14 at 05:06
  • I attempted to use it, but I'm not sure how to use it. I have never used AJAX, ever. It'd probably make things a lot easier if I did start using it. @shampoo – llw Oct 07 '14 at 05:07
  • ajax is not a weapon it is just a piece of code, how user manually refreshes the page? is there a link? – shampoo Oct 07 '14 at 05:09
  • 1
    @shampoo, `setInterval` is evil, use `setTimeout`. – Vedant Terkar Oct 07 '14 at 05:09
  • @shampoo Yes, there's currently a link for the user to manually refresh the page. I'd rather just have it automatically refresh this code itself than the whole page (and get rid of the manual refresh in general). I have no idea what i'm doing with ajax. – llw Oct 07 '14 at 05:13
  • @VedantTerkar yes yes but let the OP get a code to work then we ask him/her to visit http://www.thecodeship.com/web-development/alternative-to-javascript-evil-setinterval/. – shampoo Oct 07 '14 at 05:16
  • It comes down to a lack of understanding of AJAX. The code should be rewritten so your query is being done on a separate PHP page that `echo json_encode($assocArray);`s so JSON is sent to the AJAX `success` function on the page that holds your JavaScript. – StackSlave Oct 07 '14 at 05:39
  • in this code there is no AJAX, you are just getting information between your own server and the `https://www.toontownrewritten.com/api/invasions`. The letter J in AJAX stands for `JS` and there is only php here. – shampoo Oct 07 '14 at 05:58
  • Thanks @shampoo. I'm not sure how to rewrite the code, so I'm not going to bother with AJAX, then. – llw Oct 07 '14 at 06:06

3 Answers3

5

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 .

Community
  • 1
  • 1
shampoo
  • 1,173
  • 12
  • 22
  • is there a tutorial anywhere on how to convert the data to readable html for JS? A user on here helped me write this php code, and it works fine for manual-refresh. I'd like to utilize AJAX. – llw Oct 07 '14 at 14:51
  • do you know `console` and `console.log`? if not right clicking and choosing `inspect element` in chrome will give you an environment where you can dynamically test `js` code (google for more info). with `console.log` you can see what type you are getting, and the data is obtained this way. To make it visible to user you need jquery `append` or `html` try google and the beautiful jquery site will show up great documentation and examples. – shampoo Oct 07 '14 at 19:01
1

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){
StackSlave
  • 10,613
  • 2
  • 18
  • 35
  • What if it response don't come in 10 secs, or simply API takes more time than that to evaluate? – Vedant Terkar Oct 07 '14 at 05:11
  • What do I put for `//$.ajax();`? Do I put my PHP code I included ? – llw Oct 07 '14 at 05:12
  • Your entire methodology is wrong. Usually, when using AJAX you would do the database querying on a separate PHP page, not the one that holds your JavaScript. The `url` you refer to when using AJAX is where the PHP page should reside. You execute all your database queries with PHP, then `echo json_encode($assocArray);`. These JSON results are sent back to `AJAX` on `success`. Note: There are a number of AJAX methods. – StackSlave Oct 07 '14 at 05:26
  • @PHPglue I tried this, but it doesn't work. `` I wrapped my PHP code in `
    `. ttr-invasions.php is the separate file.
    – llw Oct 07 '14 at 05:38
  • No, you don't want to generate new loads unless you don't mind a possible flash, anyways. It might take me a second to give you a longer answer. Hold on. – StackSlave Oct 07 '14 at 05:46
  • @PHPglue My website is [here](http://www.toontownalley.com). The module on the top right (Invasions) is what I'd like to refresh automatically every 10 seconds. Another man helped me with the code to get the info from the API. I'd just like it to not be manual-refresh, but I have no experience with that. The module's file is located [here](http://www.toontownalley.com/forums/modules/invasions.php). The code for invasions.php is the exact same code in the OP. – llw Oct 07 '14 at 05:49
  • I've added a crude example. I'm not going to do your work, just head you in the right direction. – StackSlave Oct 07 '14 at 06:18
1

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);
Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48