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?
I won't write you the javascript, you should try that first yourself, but propose other solutions that might solve your primary objective (caching):
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.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.