Answer the question
In order to leave comments, you need to log in
Why is the value not being passed to php from the ajax request?
I've been sitting for an hour and I can't figure out why the console is empty
const mes = "Text";
const url = "*ссылка на php скрипт*";
fetch(url , {
method: 'POST',
data: {"text" : mes}
}).then(res=>res.text()).then(rez=>console.log(rez));
<?php
echo $_POST['text'];
?>
Answer the question
In order to leave comments, you need to log in
Since you are not passing a header with a content type, PHP does not understand that this is a post, and you need to catch the input stream.
var_dump(json_decode(file_get_contents('php://input', true)));
Because fetch doesn't have a data property in options, it's called body. Also note that if you use TypeScript - an attempt to send an object to the body field will give an error, I'm not sure if it will work as it should, if you don't wrap it in JSON.stringify(), it's better to wrap it.
In the end it should be something like this:
const mes = "Text";
const url = "*ссылка на php скрипт*";
fetch(url , {
method: 'POST',
body: JSON.stringify({"text" : mes})
}).then(res=>res.text()).then(rez=>console.log(rez));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question