Submitting Form Data Without Redirecting
To avoid page redirections caused by form submissions, jQuery Ajax provides a solution for capturing form data and sending it asynchronously to a PHP script. Here's an example:
Form (form.html):
<form>
jQuery (script.js):
// Prevent default form submission $("#foo").submit(function(event) { event.preventDefault(); // Serialize form data var serializedData = $(this).serialize(); // Send data to 'form.php' using Ajax $.ajax({ url: "form.php", type: "POST", data: serializedData, success: function(response) { console.log("Data sent successfully."); }, error: function(jqXHR, textStatus, errorThrown) { console.error(errorThrown); } }); });
PHP (form.php):
<?php // Retrieve and process posted data $bar = isset($_POST['bar']) ? $_POST['bar'] : null; // ... perform database operations using $bar ... ?>
Using this approach, you can capture form data and send it to a PHP script without page redirects or browser refresh. Remember to sanitize all posted data to prevent malicious code injection.
The above is the detailed content of How Can I Use jQuery Ajax POST to Submit a Form to PHP Without Page Redirection?. For more information, please follow other related articles on the PHP Chinese website!