简体   繁体   中英

How to access PHP super global post variable after AJAX request

I have a form in index.php:

<form action="submit.php" method="post" id="registerSubmit">
    <input type="text" name="name" id="name" placeholder="Name">
    <button id="submit" type="submit">Submit</button>
</form>
<div id="result"></div>

When the form is submitted it gets intercepted by Jquery:

$(document).ready(function(){
    $("#registerSubmit").submit(function( e ) {
    e.preventDefault();
        $.ajax({
            url: "load.php",
            method: "post",
            data: "",
            dataType: "text",
            success: function(Result) {
                $('#result').text(Result)
            }
        })

    });
});

However, when the AJAX request gets sent to load.php. I am not able to access the super global post variable:

<?php
$name = $_POST['name']; 
echo $name;
?>

I'm able to access the form data through Jquery, but I didn't want to have to parse JSON to send to Mysql. How can I access the super global post form data after the AJAX request and if it's not accessible, what are best practices for sending php form data through Ajax to Mysql?

You need to pass data through AJAX call

$(document).ready(function(){
    $("#registerSubmit").submit(function( e ) {
    e.preventDefault();
        $.ajax({
            url: "load.php",
            method: "POST",
            data: $(this).serialize(), // Send all form data to AJAX
            dataType: "text",
            success: function(Result) {
                $('#result').text(Result)
            }
        })

    });
});

You need to pass data through AJAX call When the form is submitted.

 $(document).ready(function(){
        $("#registerSubmit").submit(function( e ) {
        e.preventDefault();

        var name = document.getElementById("name").value;
        var dataString ='name=' + name;
            $.ajax({
                url: "load.php",
                method: "post",
                data: "dataString",
                dataType: "text",
                success: function(Result) {
                    $('#result').text(Result)
                }
            })

        });
    });


In the load.php page

<?php
$name = $_POST['name']; 
echo $name;

// code for insert in mysql with PHP.

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM