I am sending data to a page using javascript fetch and I get the ok message in the console. How can I get this data on the php page I sent?
fetch("test.php", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
user_id: user_id,
value: valueToSend
})
})
.then(
function(response) {
if (response.ok) {
console.log("ok)
} else {
console.log("There was an error sending the message.", response);
}
}
);
I'm asking this. I will use the user_id and value values in the test.php page, but how can I get this data there? So what should I do from the test.php page?
CodePudding user response:
OK, so you are actually looking to get the values once they are sent to the test.php. You don't care about the response.
The simplest way would be to use the $_GET
and $_POST
objects.
in you case it would look something like
<?php
echo($_POST['user_id'])
echo($_POST['value'])
?>
This very simple example just prints the two vars that you sent. You can perform your logic here.
You are posting the data to the page, so php makes them available in $_POST
. From there you can do with them what you wish.
Edit
If you are trying to view previously sent data (data sent by fetch on a different request) you will need to store that data when it gets to index.php
.
window.location.href works because you are redirecting to the php page and giving it values via the query string.
Either write it to a file, store it in a DB, or put it in memory.
<?php
if ($_POST['user_id'] != '') {
#some sort of logic here to store the data that was just received.
# This could be a database, writing the data itself to a file, etc.
} else {
# Logic to retrieve the data from store and display it.
# You could retrieve the data from a database/file and then use `echo` to display it.
}
?>
CodePudding user response:
Depending on what kind of data is being returned you can use the .text()
or .json()
methods for your response.
fetch("test.php", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
user_id: user_id,
value: valueToSend
})
})
.then(response => {
if(response.ok) {
console.log("ok");
let r = response.text();
try { r = response.json();
} catch(e) { }
return r;
} else {
console.log("There was an error sending the message.", response);
}
})
.then(r => {
console.log(r);
});
CodePudding user response:
It depends on the data you are trying to get. If for example if it was JSON
fetch("test.php", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
user_id: user_id,
value: valueToSend
})
})
.then(
function(response) {
if (response.ok) {
console.log("ok")
return(response.json()) // The important bit. Grabs the response as JSON.
} else {
console.log("There was an error sending the message.", response);
}
}
).then(
function(data) {
//Does something with the data
}
)