Home >Web Front-end >JS Tutorial >How to Submit Form Data Without Page Refresh Using jQuery and PHP?

How to Submit Form Data Without Page Refresh Using jQuery and PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 15:17:10988browse

How to Submit Form Data Without Page Refresh Using jQuery and PHP?

Submitting Form Data via Ajax with jQuery and PHP (form.php)

To prevent browser redirection when submitting forms, you can leverage jQuery and Ajax. Here's how to achieve this for a form like the one provided:

<form>

jQuery:

$(document).ready(function () {
    $('#foo').submit(function (event) {
        event.preventDefault();
        var $form = $(this);
        var $inputs = $form.find('input, select, button, textarea');
        var serializedData = $form.serialize();
        $inputs.prop('disabled', true);
        $.ajax({
            url: '/form.php',
            type: 'post',
            data: serializedData,
            done: function (response) {
                console.log('Hooray, it worked!');
            },
            fail: function (jqXHR, textStatus, errorThrown) {
                console.error(
                    'The following error occurred: ' +
                        textStatus,
                    errorThrown
                );
            },
            always: function () {
                $inputs.prop('disabled', false);
            }
        });
    });
});

PHP (form.php):

// Access posted data through $_POST
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;

You can also use the shorthand .post instead of .ajax in jQuery:

$.post('/form.php', serializedData, function (response) {
    console.log('Response: ' + response);
});

Tips:

  • Sanitize posted data to prevent malicious injections.
  • Place the jQuery code within a $(document).ready() handler.
  • You can chain callback handlers (done(), fail(), always()) for more control.

The above is the detailed content of How to Submit Form Data Without Page Refresh Using jQuery and PHP?. 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