How to Post Parameters To PHP Using Fetch API and Update DOM with JSON response

The following is a simple example of how to post multiple parameters to a backend PHP script, take the returned JSON and update DOM with it.

HTML

<h2>
How to Post Parameters To PHP Using Fetch API and Update DOM with JSON response
</h2>

<button onclick="loadJSON('days=3&user=7')">Post days:3, user:3</button> or
<button onclick="loadJSON('days=7&user=7')">Post days:7, user:3 </button>

<br><br>

<div id="fetch"></div>

Javascript:

let $div_fetch = document.querySelector('#fetch');


function loadJSON(params) {
var myObj, x, htmlResult = "";
var url = 'http://jarosciak.com/test.php';
console.log(params);
	fetch(url, {
 	method: "POST",
 	headers: {
 'Accept': 'application/json, text/plain, */*',
 "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
 },
 body: params
 })
.then(function (response) {
return response.json();
})
.then(function (myJson) {
console.log(myJson);
myObj = JSON.parse(JSON.stringify(myJson));
for (x in myObj) {
htmlResult += myObj[x].created_at + " - <b>" + myObj[x].PhysicalScore + "</b><br>";
}
$div_fetch.innerHTML = htmlResult;
});
}

PHP that accepts POST method:

<?php
header('Access-Control-Allow-Origin: *'); 
header("Content-Type: application/json; charset=UTF-8"); 

$obj_days = $_POST["days"];
$obj_user = $_POST["user"];

// $obj_days test only:

if ($obj_days == 3)
{
echo '[{"created_at":"2020-06-29","PhysicalScore":" "},{"created_at":"2020-06-30","PhysicalScore":"8"},{"created_at":"2020-07-01","PhysicalScore":"7"}]';
}

if ($obj_days == 7)
{
echo '[{"created_at":"2020-06-29","PhysicalScore":" "},{"created_at":"2020-06-30","PhysicalScore":"8"},{"created_at":"2020-07-01","PhysicalScore":"7"},{"created_at":"2020-07-02","PhysicalScore":"6"},{"created_at":"2020-07-03","PhysicalScore":" "},{"created_at":"2020-07-04","PhysicalScore":" "},{"created_at":"2020-07-05","PhysicalScore":" "}]';
}
?>

And here is a working code at JSFIDDLE:

http://jsfiddle.net/jarosciak/a27thwLp

 

Facebook Comments