P粉8262835292023-08-31 10:38:50
Finally I managed to solve the problem, explained below:
datosJS.js
window.onload = function() { let datos = { method: "POST", headers: { "Content-type" : "application/json" }, body: JSON.stringify({ username:"Jonathan", email:"jonathan@gmail.com", password:"123456" }) } fetch('Test.php',datos) .then(resp => resp.text()) .then(resp =>{ console.log(resp); document.getElementById('results').innerHTML = resp; //document.querySelector('#results').innerHTML = resp; // works as well as getElementById }) }
test.php
<script src="datosJS.js" type="text/javascript"></script> <section class="Section" id="results" name="results"> <?php $body = json_decode(file_get_contents("php://input"), true); $nombre = $body['username']; echo $nombre; echo '</br>'; print_r($body); ?>
Below I will mark what is missing in the original code:
In datosJS.jsdocument.getElementById('results').innerHTML = resp; and wrap everything in window.onload = function() {} middle
In Test.php add id="results" name="results" to div, section or other content from innerHTML take over.
I hope it helps someone in the future. cheers