Calling a PHP function from a JavaScript function allows for integration between the server-side and client-side code. Here's how to achieve this:
AJAX (Asynchronous JavaScript and XML) enables communication between JavaScript and a server without refreshing the entire page. When an event on the web page triggers a request, AJAX sends an asynchronous request to a PHP file. The response from the server is then used to modify the relevant section of the page.
JavaScript:
function callPHP() { $.ajax({ url: 'my_script.php', method: 'POST', data: { name: 'John Doe' }, success: function(data) { // Process the PHP function output and display it }, error: function() { alert('Error calling the PHP function'); } }); }
PHP:
function greet($name) { return "Hello, $name!"; } if (isset($_POST['name'])) { echo greet($_POST['name']); }
By following these steps, you can seamlessly integrate server-side and client-side functionality by calling PHP functions from JavaScript functions.
The above is the detailed content of How Can I Call a PHP Function from JavaScript?. For more information, please follow other related articles on the PHP Chinese website!