JSON PHP Ajax Post Dynamic Variable Data Tutorial
In this part of the JSON programming series we extend the dynamics from the last exercise by changing our Ajax request to a post method. It opens up more dynamic possibilities for JSON data requesting by allowing dynamic variable data to be posted to the PHP script that is going to render the JSON data. One could use the posted variable data in a database query to fetch specific data to return to the program in JSON format.
my_json_list.php
<?php
header("Content-Type: application/json");
$var1 = $_POST["var1"];
$var2 = $_POST["var2"];
$jsonData = '{ "obj1":{ "propertyA":"'.$var1.'", "propertyB":"'.$var2.'" } }';
echo $jsonData;
?>
JSON_tutorial_4.html
<!DOCTYPE html>
<html>
<head>
<script>
function ajax_get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("POST", "my_json_list.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
results.innerHTML = "";
for(var obj in data){
results.innerHTML += "Property A: "+data[obj].propertyA+"<hr />";
results.innerHTML += "Property B: "+data[obj].propertyB;
}
}
}
hr.send("var1=birds&var2=bees");
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script>ajax_get_json();</script>
</body>
</html>