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
Release: 2024-12-23 15:17:10
Original
1014 people have browsed it

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>
Copy after login

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);
            }
        });
    });
});
Copy after login

PHP (form.php):

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

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template