Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 525
chustar Avatar asked Aug 15 '09 00:08

chustar


People also ask

Can I call PHP function on button click?

Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists() function called.

Why must PHP scripts be run through a URL?

Having a web server running on your local computer isn't necessary for developing HTML, CSS, or most JavaScript applications. But because a browser can't interpret PHP, a local web server is essential if you want to write PHP scripts on that computer and run them without uploading them to a server somewhere.


2 Answers

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

like image 128
Parrots Avatar answered Oct 17 '22 20:10

Parrots


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

like image 44
Roy Rico Avatar answered Oct 17 '22 21:10

Roy Rico