FULL STACK   ·   UI   ·   UX   ·   GRAPHICS   ·   DEVELOPER   ·   INSTRUCTOR

Adam Khoury

Donate funds to show love and support

Click the button below to donate funds securely online. You can use your PayPal account or a credit card.

Your donations help free up my time to produce more content and assist in covering server costs. It's also a great way to say thanks for the content!

Application Configuration

Adam will be adding options here soon.

JSON PHP Ajax Post Dynamic Variable Data Tutorial

Published :
Author :
Adam Khoury
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>