xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); let text = “”; for (let x in myObj) { text += myObj[x].name + “<br>”; } document.getElementById(“demo”).innerHTML = text; } |
When sending data to the server, it’s often preferable to use the HTTP POST method.
To send AJAX requests using the POST method, specify the method and set the appropriate header.
The data being sent to the server should now be provided as an argument to the send()
method.
const dbParam = JSON.stringify({“limit”:10}); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); let text =“”; for (let x in myObj) { text += myObj[x].name + “<br>”; } document.getElementById(“demo”).innerHTML = text; } xmlhttp.open(“POST”, “json_demo_db_post.php”); xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”); xmlhttp.send(“x=” + dbParam); |
The only difference in the PHP file is the method used to retrieve the transferred data.
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”); $stmt = $conn->prepare(“SELECT name FROM customers LIMIT ?”); $stmt->bind_param(“s”, $obj->limit); $stmt->execute(); $result = $stmt->get_result(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?> |