\n\n\n\n\n\n\n\nPHP backend (server.php):\nphp\n\n\n\nThe script presents jQuery sending a POST request to \"server.php\". This strikes the chord and ExecuteFunction() springs in action, echoing its result. Capture this echo from the void within your jQuery post() method callback.","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Nikita Barsukov","url":"https://explain.codes//author/nikita-barsukov"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2024-09-13T20:45:01.411Z","dateModified":"2024-09-13T20:45:02.672Z"}
Explain Codes LogoExplain Codes Logo

How to call a PHP function on the click of a button

javascript
ajax
best-practices
javascript-8
Nikita BarsukovbyNikita Barsukov·Sep 13, 2024
TLDR

Let's trigger a PHP function upon button click using AJAX and the power of jQuery. This code snippet shows how a jQuery POST request can engage your PHP function without reloading the page:

<!-- Adding the mighty jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Our humble button --> <button id="triggerPhp">Poke the PHP function</button> <script> // When button is clicked, magic happens $('#triggerPhp').on('click', () => { $.post("server.php", { action: 'callThisFunction' }, function(response) { console.log(response); // Echoes from PHP, a whisper across the void }); }); </script>

PHP backend (server.php):

<?php if ($_POST['action'] == 'callThisFunction') { // The function comes to life! echo ExecuteFunction(); } function ExecuteFunction() { // Heart of your PHP function return 'Function, arise from thy slumber!'; } ?>

The script presents jQuery sending a POST request to "server.php". This strikes the chord and ExecuteFunction() springs in action, echoing its result. Capture this echo from the void within your jQuery post() method callback.

User experience: Let's add sugar and spice

A pat on the back: Make your users smile! Show an alert or tweak the DOM to show that the PHP function did its dance:

$('#triggerPhp').on('click', () => { $.post("server.php", { action: 'callThisFunction' }, function(response) { alert("PHP function just did a flip!"); // Like a gymnast! }); });

Prevent page refresh: Ensure your buttons aren't mingling inside a <form> with its default behaviour, or they'll summon an unwanted page refresh:

<!-- A free bird, unbound by forms --> <button id="triggerPhp">Poke the PHP function</button>

Cleanliness is next to godliness: Code organization

Separation of powers: Define clear boundaries. Reserve HTML/JavaScript for your client-side stories and PHP for server-side sagas. Trust me, future you will thank the present you for this.

Exclusive VIP entry: Be the bouncer for your server-side party. Check the guest's pass (method type):

<?php if ($_SERVER['REQUEST_METHOD'] == "POST") { // Welcome to the POST party } ?>

Uniqueness is key: Each action needs a unique tag. Avoid "John Doe" tags when juggling multiple buttons/forms, or you'll enter the realm of confusion.

Hustling with AJAX errors

Expect the unexpected: AJAX will throw a curveball at you. Don the hat of a global manager, catch those scenarios:

$.post("server.php", { action: 'callThisFunction' }) .done(function(response) { // Success is sweet, savor it }) .fail(function(jqXHR, textStatus, errorThrown) { console.error('Calling PHP function, or trying to wake a sloth? Error: ' + textStatus); });

Handle with care: Make errors look less like a haunted house and more like a boo-boo. For users, replace error logs with friendly messages or soft fallbacks:

.fail(function() { alert("Oopsie daisy! Try again after a coffee break."); });

Embracing best practices

Roles clear as crystals

Know your members: HTML and JavaScript are client-side artists and PHP is the server-side maestro. Let them create their own music.

Input attributes: Our unsung heroes

Use input attributes wisely. Opt for type="submit" for form-submitting buttons and name attributes to tell one button from another.

Security: The absolute monarch

Follow the golden rule of data validation—don't trust user input. Employ defensive techniques like validating, sanitizing, and escaping data.

Code modularity: Your golden goose

Break your code into bite-sized, standalone modules. Make your codebase more readable, reusable, and testable.