Reputation: 9220
I'm going to make a live scoring table which shows scores from a database obviously i'm going to do it with jquery ajax but i'm wondering what is a good practice on doing this.
Is it a good idea to return an array, or object with all the scores and use javascript or jquery to build the table: Meaning that i loop over the result and create a tr or td where needed.
Or should i build the table in php, and spit out the whole contents on the webpage. I think the only problem here is that you have no real control over the content, if I maybe would like to animate a row getting deleted.
I'm kindoff stuck on this. Ideally I would love to make it that if a score changes, The row get's animated to a fade out and the new score comes in place.
So that's why I'm asking some insights and opinions on how to achieve this.
Thanks!
Upvotes: 2
Views: 1667
Reputation: 14851
I think it's best for AJAX to read just a JSON, and nothing else. That way, you can make it a part of the REST API. Then have your script render the table using DOM operations. This is what modern frameworks such as Angular and Backbone do anyway.
Now, about the ways you could accomplish the data retrieval.
In a scenario like this what I usually do is to create a script that is responsible only for updating the data. For example:
<?php
$data = ...
file_put_contents(__DIR__ . '/data/scores.json', json_encode($data));
Then I add this script to cron, so that it gets executed in interval I desire.
* * * * * php myscript.php
Finally, the JS script retrieves just the /data/scores.json
file, without touching server-side code at all.
In your case you want to run the script very often (every 5 seconds). Cron is capable of running tasks every minute at most, however, you can use some workarounds to get it execute the script more often.
Now let us discuss some disadvantages of such approach.
That leads us onto another approach, which was already discussed in the comments...
You can have your AJAX query scores.php
that does following:
<?php
if (isCacheValid())
{
$data = readCache();
}
else
{
$data = ...
saveCache($data);
}
echo json_encode($data);
The advantage of such approach is that:
Querying your database every few seconds is a perfectly normal state for database to be in and you shouldn't worry about it... unless you query tables contain multiple thousands/millions of rows.
Don't optimize early. Measure and then figure whether the solution is satisfactory, or it needs working on.
Upvotes: 2