Home > Web Front-end > JS Tutorial > How Can I Use jQuery Ajax POST with PHP to Submit a Form Without Page Redirect?

How Can I Use jQuery Ajax POST with PHP to Submit a Form Without Page Redirect?

Mary-Kate Olsen
Release: 2024-12-24 05:52:14
Original
904 people have browsed it

How Can I Use jQuery Ajax POST with PHP to Submit a Form Without Page Redirect?

jQuery Ajax POST with PHP: An Example

Submitting data from a form to a database often necessitates a form submission, which causes a browser redirect. Using jQuery and Ajax, it is possible to overcome this by capturing form data and submitting it to a PHP script.

jQuery Code:

The jQuery code is as follows:

<form>
Copy after login
// Prevent form submission
$("#foo").submit(function(event){
    event.preventDefault();
    
    // Serialize form data
    var serializedData = $("#foo").serialize();
    
    // Ajax request
    $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData,
        success: function (response) {
            console.log("Request successful");
        },
        error: function (error) {
            console.error("Error:", error);
        }
    });
});
Copy after login

PHP Script:

The PHP script (form.php) receives the submitted data:

<?php
    $bar = isset($_POST['bar']) ? $_POST['bar'] : null;
?>
Copy after login

Usage:

Wrap your JavaScript code in a document-ready handler:

$(document).ready(function(){
    // jQuery code
});
Copy after login

Remember to sanitize input when working with user-submitted data.

Shorthand with jQuery .post:

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

This method can be used with jQuery versions 1.5 and above.

The above is the detailed content of How Can I Use jQuery Ajax POST with PHP to Submit a Form Without Page Redirect?. 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