Friday, May 11, 2018

PHP Method=POST

When sending data to the server, it is often best to use the HTTP POST method.
To send AJAX requests using the POST method, specify the method, and the correct header
The data sent to the server must now be an argument to the send() method:

obj = { "table":"customers""limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        for (x in myObj) {
            txt += myObj[x].name + "<br>";
        }
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST""json_demo_db_post.php"true);xmlhttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

The only difference in the PHP file is the method for getting the transferred data.

PHP file
Use $_POST instead of $_GET:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_POST["x"], false);

$conn = new mysqli("myServer""myUser""myPassword""Northwind");
$result = $conn->query("SELECT name FROM ".$obj->table." LIMIT ".$obj->limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($outp);
?>

No comments:

Post a Comment