I have a script that I load via Ajax on every page of my site. It shows locally-sold ads, and I have it set to load after everything else so that it doesn't slow down the delivery of content.
The script shows 3 ads at a time, then as the user scrolls down (infinite scroll) the script runs again when there's room. So it could run one time on a page, or 50 times.
Currently, I run a MySQL query at the beginning of the page and randomize the order of the results, I push all of the ad data to a PHP variable that I then JSON encode, and then add that data to the URI for the Ajax request. I keep track of each time the Ajax script loads, and send that number to the script so that it starts showing ad data at that number. This way, an ad doesn't repeat until all of them have been shown.
What I have works fine, but since I lazy load the ads I would like to find a way to move the MySQL query to that script, too... no need to add another microseconds to the beginning when it could be pushed to the end, right? It's also entirely possible that the script won't be run at all (if I don't have any advertisers for that particular section), in which case the query would be a total waste of time and resources (on my already overloaded server).
But can you guys and gals suggest a way to lazy load the MySQL query, then store it on the page for all other Ajax-driven requests on the page? I can't store it long-term because a new advertiser could sign on, and I don't want them ignored for the duration of the user's session. And I don't want to run it anew at each iteration of the Ajax scripts unless I can figure out a way to not repeat a banner until all of them have been shown.
My initial thought is getting complicated... since I'm already using jQuery, I could put the MySQL query in its own script and use
$.get('query.php', function(data) { ... }); to store it as a variable, then send that variable to the other Ajax scripts:
// untested, just typed up for this
var addata;
$.get('query.php', function(data) {
if (data)
addata = data;
});
// then at the Ajax location
$('#example').ajax('ad_script.php?addata=' + addata);
But then I would have to somehow code the first iteration of the Ajax script to not run until query.php has returned something. So before I go down that rabbit hole, is there an easier way to lazy load the MySQL before running the Ajax scripts?
I'm putting this in "General" because the solutions could be in JavaScript / jQuery, PHP, or even MySQL...