I want to send a data object with fetch api with keepalive to the current page and get the data through php. how can I do it.
Data To Send
{
name: 'blabla',
age: 432,
type: 'pig'
}
I want to recieve as a post variable
$_POST['name'];
I've tried this but it is not working
fetch('', {
method: 'POST',
body: {name: 'blabla'},
keepalive: true
});
Sorry for no code
No idea what keepalive is, but if I want to send a fetch request to a php backend I would usually do something like this:
fetch("backend.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body: "data=" + data,
})
.then((response) => response.json())
.then((response) => doWhatYouWant(response))
.catch((error) => alert("Error : " + error));
You could call fetch with json as content-type and use method POST as you allready tried, you also have to serialize the content on the body
fetch("backend.php", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: "blablabla" }),
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.