-1

I'm new to coding and was pretty proud when I created the following PHP code. Using TwitchTV's API, I can show the game someone is playing on TwitchTV. It works.

$info = "https://api.twitch.tv/kraken/channels/celgaming";   
$json = json_decode(file_get_contents($info), true);
$thegame = $json['game'];
echo $thegame;

But I'm planning on caching the page this code is on and realized it won't work because PHP is server side. How do I convert this piece of code to Ajax or some other asynchronous method that will work with page caching?

  • 2
    In my onion, what you are asking for is too much for SO. You are asking for people to write a part of a program, rather than fix/help with one aspect, which is what SO is for. Typically people will use a JavaScript framework, like jQuery, for AJAX. Using this, you include the – Kohjah Breese Aug 25 '14 at 20:08
  • Yeah not many people will take this question celery. Try looking at the docs first and check back with us if you need help. At the moment, it doesn't look like you've put the effort down yet. – Dave Chen Aug 25 '14 at 20:13
  • Another problem you may have is that you won't be able to run a traditional AJAX query as you are not requesting data that is on the same domain. Furthermore, I am not completely convinced about how helpful AJAX would be over PHP as far as caching is concerned? – ornous Aug 25 '14 at 20:13
  • @SnakeFast he need only XMLHTTPRequest for IE =>10 and others browsers, XDomainRequest for IE8/IE9 to perform a CORS request. – Bob Aug 25 '14 at 20:47

2 Answers2

0

I won't write you the javascript, you should try that first yourself, but propose other solutions that might solve your primary objective (caching):

  • you may use a database (e.g. MySQL) instead of client side caching. Just store the result of your TwitchTV query together with an expiration date in your database and check it before sending another request to TwitchTV.
  • you could send HTTP Cache-Control headers via PHP or included in your HTML code. See this question for instructions: Cache control and expires header for PHP. They suggest to the client to no query the server before the expiration date is reached.
Beat
  • 1,337
  • 15
  • 30
0

I´m not sure about an async call being what you need, but I would try that first. Here is, not a real answer, but hopefully some pointers to it:

Tried to make an Ajax call to "https://api.twitch.tv/kraken/channels/celgaming" and stumbled upon 'same-domain policy' issue. See below link.

[Solutions to Ajax cross-domain problem][1]

I tried this from [1]: Ways to circumvent the same-origin policy

$.getJSON("https://api.twitch.tv/kraken/search/games?q=star&type=suggest&callback=?", function (data) {
            $.each(data.games, function (index, item) {
               console.log(index, item);
            });
        });

It works. Maybe you should scan the API docs for an alternate way to get the data you need.

Community
  • 1
  • 1
nocarrier
  • 129
  • 6