How do I run PHP code when a user clicks on a link? How do I run PHP code when a user clicks on a link? php php

How do I run PHP code when a user clicks on a link?


Yeah, you'd need to have a javascript function triggered by an onclick that does an AJAX load of a page and then returns false, that way they won't be redirected in the browser. You could use the following in jQuery, if that's acceptable for your project:

<script type="text/javascript" src="jquery.min.js"></script><script type="text/javascript">function doSomething() {    $.get("somepage.php");    return false;}</script><a href="#" onclick="doSomething();">Click Me!</a>

You could also do a post-back if you need to use form values (use the $.post() method).


As others have suggested, use JavaScript to make an AJAX call.

<a href="#" onclick="myJsFunction()">whatever</a><script>function myJsFunction() {     // use ajax to make a call to your PHP script     // for more examples, using Jquery. see the link below     return false; // this is so the browser doesn't follow the link}

http://docs.jquery.com/Ajax/jQuery.ajax


If you haven't yet installed jquery (because you're just a beginner or something), use this bit of code:

<a href="#" onclick="thisfunction()">link</a><script type="text/javascript">function thisfunction(){    var x = new XMLHttpRequest();    x.open("GET","function.php",true);    x.send();    return false;}</script>