P
P
Pavel Sachenko2020-05-01 17:49:22
PHP
Pavel Sachenko, 2020-05-01 17:49:22

How to send data using the fetch method and get the correct response?

How can I send data using the fetch method to php so that they end up in the $_POST variable.
In the javascript file I have the code:

async function post(url) {
    let form = takeFormControl();
    let test = {name: "test"};
    let response = await fetch(url, {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(test),
    });
    let result = await response.json();
    console.log(result);
}


function takeFormControl(){
    let form =  document.querySelector(".form-control");
    form.addEventListener("click", (e) => {
        e.preventDefault();
    });
    return form;
}


php code:
if (isset($_POST['name'])){
    echo json_encode(['status' => 'good', $_POST]);
}else{
    echo json_encode(['status' => 'bad', $_POST, $_REQUEST]);
}

The result is constantly: "status - bad", and there is nothing in the variables

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
origami1024, 2020-05-01
@PavelSachenko

$_POST['name'] - this would be recognized if you sent the variable as form_data
You are sending just raw data
To see what you get as PHP input use PS json_decode it won't work as it's not a valid json. Valid json looks like this: {"name": "test"}
file_get_contents('php://input')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question