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

chustar picture chustar · Aug 15, 2009 · Viewed 255.2k times · Source

I want to have a page run some PHP code when a user clicks on a link, without redirecting them. Is this possible with

<a href=""></a>

or with the javascript onclick event?

Answer

Parrots picture Parrots · Aug 15, 2009

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).