Obtaining data from PHP file returns null value
P粉617237727
P粉617237727 2023-08-30 11:20:14
0
1
416

I'm trying to test and learn how fetch works so I want to send some data from javascript to a php file, my problem is that I can't retrieve the data (in the php file) and only get a null response.

I'm using POST, but I tried using GET and got the same result

As a side note, in the console, the connection in the network only appears after I press F5, which I understand should already be working when I open Test.php.

datosJS.js

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); })

Test.php

 //I use this to call "datosJS.js" to receive the data here in Test.php 

I know that PHP is on the server side and JS is on the client side, and that they both run at different times, but I'm having trouble finding a solution to this problem.

Thanks for your help!

** Edited a small change in fetch that now allows me to view the data in the console

P粉617237727
P粉617237727

reply all (1)
P粉826283529

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

 
'; print_r($body); ?>

Below I will mark what is missing in the original code:

  • In datosJS.jsdocument.getElementById('results').innerHTML = resp;and wrap everything inwindow.onload = function() {}middle

  • In Test.php addid="results" name="results"todiv,sectionor other content from innerHTML take over.

I hope it helps someone in the future. cheers

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!