Home >Web Front-end >JS Tutorial >How Can I Submit a Form Using jQuery Ajax POST without Page Refresh?

How Can I Submit a Form Using jQuery Ajax POST without Page Refresh?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 08:28:35502browse

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 jQuery shorthand .post can be used instead of .ajax.
  • Remember to sanitize form data on the server-side.
  • This code is compatible with jQuery versions 1.8 and later.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn