6
6
6ondawave92022-04-07 14:35:43
AJAX
6ondawave9, 2022-04-07 14:35:43

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

2 answer(s)
T
ThunderCat, 2022-04-07
@6ondawave9

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

N
Ne7Le4Der, 2022-04-07
@Ne7Le4Der

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 question

Ask a Question

731 491 924 answers to any question