简体   繁体   中英

differentiating between post requests

I have this jquery function which sends a POST request to the server

function loadInfo() {
    jQuery(function($) {
        $.ajax({
            method: "POST",
            url: "/admin.php",
            dataType: "json",
            success: function(data) {
                console.log(data);
                for (var i = 0; i < data.length; i++) {
                    setMarker(data, i, "red");
                    printInfo(data, i);
                }
            }
        })
    });
}

This is how the request gets handled

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    header('Content-Type: application/json');
    require 'private/database.php';

    $sql = "SELECT * FROM form";
    $result = mysqli_query($conn, $sql);

    $data = array();
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
    }
    die(json_encode($data));
}

The code works, but what if I have send multiple POST requests to the same server? Is there a way to differentiate between them like how you would when handling HTML forms? eg If the of the button that submits the form is "submit_button"...

if (isset($_POST['submit_button'])) {
   ...
}

You have to send some parameter to differentiate the request.

eg:     $.post( "test.php", { name: "John", time: "2pm", method:"formSubmit" } );

There are a number of ways to send post by AJAX with data (multiple data items). One of the ways is:

 $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {status: "ok", name: "Richard"},
                success: function (result) {
                    alert('success');
                } 
})

In the above case, you have sent status and name data to the php script by POST method. Hope that it can answer your question.

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