Dynamically changing PHP variables
I have a website that grabs a random entry from a database a开发者_开发知识库nd displays it for the viewer. This is the code I am currently using:
$rows = "SELECT * FROM xxx";
$rows1 = mysql_query($rows);
$rows2 = mysql_numrows($rows1);
$id= rand(1, $rows2);
This generates an ID number which is used to select a corresponding database entry, and of course there is more php that displays the entry.
In order for the user to generate a new entry from the database, they click a button which refreshes the page using this code:
<form>
<input type=button value="Show me another one" onClick="window.location.reload()">
</form>
This works fine but it's causing a problem with Google Adsense; it causes Adsense to record huge numbers of page impressions from a given individual user. I haven't had any correspondence with Google about it, but it must look like I am gaming the system for advertisers who pay "per impression". I am worried that this is resulting in Google automatically preventing me from receiving revenue from "per impression" advertisements, and may result in my Adsense account being revoked.
So my question is how can make a button that will pull a different entry from the database without refreshing the page? Essentially, I need to find a way to change the "$id" variable after a user clicks the button.
You have a couple ways to achieve what you're trying to do.
If you want to keep it down to earth HTML and PHP, you can solve your problem by having an IFRAME in your page, with your reload button inside. Of course, you would then not insert the google tracker in the page opened by the IFRAME. You can conceal the IFRAME poor default styling with a little bit of CSS, so it doesn't stand out your existing page.
That is far from being the best way to handle this however.
You should, as suggested by deceze, resort to Ajax to fetch dynamically new information through Javascript. In order to handle this as painlessly as possible, I suggest you choose a Javascript framework to leave all the annoying cross browser bits to it.
For instance, with jQuery you can do the following (HTML + javascript)
<!-- new content will appear in the div down below -->
<div id="content-target">
</div>
<form>
<input type="button" id="refresher" />
</form>
<script type="text/javascript">
$('#refresher').click(function(){
$('#content-target').load('generator.php');
return false;
});
</script>
You should spend some time learning a JS framework. It's a very good investment.
For jQuery: http://jquery.com/
Prototype: http://www.prototypejs.org/
MooTools: http://mootools.net/
Dojo: http://www.dojotoolkit.org/ (overkill for this kind of script)
精彩评论