1

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?

4
  • And that PHP variable is where (relative to the page with the ANCHOR)? Commented Mar 1, 2011 at 23:39
  • 2
    PHP 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? Commented 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.post Commented 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. Commented Mar 1, 2011 at 23:57

2 Answers 2

7

JavaScript is Client Side. PHP is Server Side. If you want to affect a PHP Variable with a JavaScript event you must issue an AJAX call of some kind.

Sign up to request clarification or add additional context in comments.

Comments

1

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' );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.