Home >Web Front-end >JS Tutorial >How Can I Submit a Form Using jQuery Ajax POST without Page Refresh?
jQuery Ajax POST Example with PHP
This example demonstrates how to send form data to a PHP script using jQuery's Ajax capabilities.
The Problem
When submitting a form using the traditional method, the browser redirects to the specified action URL. However, we want to capture the form data and submit it to a PHP script without causing a page refresh.
The jQuery and Ajax Solution
jQuery's .ajax method allows us to make asynchronous requests to the server. Here's how we can use it to send form data:
HTML:
<form>
jQuery:
$("#foo").submit(function(event) { event.preventDefault(); var $form = $(this); var serializedData = $form.serialize(); $.ajax({ url: "/form.php", type: "post", data: serializedData, done: function (response, textStatus, jqXHR) { console.log("Hooray, it worked!"); }, fail: function (jqXHR, textStatus, errorThrown) { console.error("The following error occurred: " + textStatus, errorThrown); }, always: function () { // Reenable form inputs } }); });
PHP (form.php):
// Access form data via $_POST $bar = isset($_POST['bar']) ? $_POST['bar'] : null;
This solution uses the .done() and .fail() callback handlers to handle the success and failure scenarios respectively. The .always() callback is called regardless of the outcome of the request.
Additional Notes:
The above is the detailed content of How Can I Submit a Form Using jQuery Ajax POST without Page Refresh?. For more information, please follow other related articles on the PHP Chinese website!