I have a link like this: <a href="javascript:window.print();">Print</a>. I'm trying to increment a PHP variable when that is clicked. I could technically do it by submitting a form, but I'm sure there is an easier way. Any ideas?
-
And that PHP variable is where (relative to the page with the ANCHOR)?Šime Vidas– Šime Vidas2011-03-01 23:39:07 +00:00Commented Mar 1, 2011 at 23:39
-
2PHP Variable? As in something that only exists for the duration of PHP executing (with the exception of a session/cookie). Are you sure you don't mean a DB variable, accessible through PHP?Brad Christie– Brad Christie2011-03-01 23:43:59 +00:00Commented Mar 1, 2011 at 23:43
-
Yeah like @Brad Christie and @g.d.d.c have mentioned, use a database and AJAX. JQuery is good for that api.jquery.com/jQuery.postlogic-unit– logic-unit2011-03-01 23:55:09 +00:00Commented Mar 1, 2011 at 23:55
-
Remove the js from the href and add an onclick="incrementFunction();return false" to the attributes. That function then calls the JQuery AJAX that runs a PHP script, which updates the database. A new value (+1 hopefully) is returned and displayed.logic-unit– logic-unit2011-03-01 23:57:27 +00:00Commented Mar 1, 2011 at 23:57
Add a comment
|
2 Answers
You'll need to persist a variable like this using some sort of database. You can then issue an AJAX call to a small server-side file that increments a value in that database.
On your HTML page:
<script type="text/javascript">
$(document).ready(function() {
$('#print').click(function() {
$.getJSON('http://somewhere.com/increment.php', null, function(data) {
console.log('remote increment script returned: ' + data);
});
window.print();
});
});
</script>
<a href="javascript: void 0;" id="print">Print</a>
Then, server-side in /increment.php (I assumed MySQL, but you could use something else like Redis for this as well):
// database connection goes here
$result = mysql_query("UPDATE stats SET stat_value = stat_value + 1 WHERE stat_key = 'prints'", $some_database_connection);
mysql_close($some_database_connection);
die( $result ? 'true' : 'false' );