Home > Article > Backend Development > How to Execute PHP Code on Link Click Without Redirection?
Execute PHP Code on Link Click Without Redirection
When working with web pages, it may be necessary to seamlessly execute PHP code in response to a user clicking on a link. This question delves into how to achieve this without incurring a page redirection.
Using JavaScript
The provided solution involves utilizing JavaScript's onclick event in conjunction with AJAX. By loading a PHP page using AJAX, the browser can execute the code in the background without interrupting the user's current page view.
Here's an example using jQuery:
<code class="javascript"><script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript"> function doSomething() { $.get("somepage.php"); return false; // Prevent page redirection } </script> <a href="#" onclick="doSomething();">Click Me!</a></code>
In this example, clicking the link triggers the doSomething() function, which asynchronously loads the "somepage.php" script and returns false to prevent redirection.
Using Form Submission
If form values need to be submitted to the PHP code, AJAX can be adapted for use with the $.post() method.
The above is the detailed content of How to Execute PHP Code on Link Click Without Redirection?. For more information, please follow other related articles on the PHP Chinese website!