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
Mary-Kate OlsenOriginal
2024-12-24 05:52:14946browse

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>
// 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);
        }
    });
});

PHP Script:

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

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

Usage:

Wrap your JavaScript code in a document-ready handler:

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

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

Shorthand with jQuery .post:

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

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!

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