I
I
ilyabond2021-01-21 23:07:26
PHP
ilyabond, 2021-01-21 23:07:26

Why doesn't PHP accept JSON sent via AJAX?

Sorry if this is a dumb question, I've been looking for a solution but haven't found anything yet. I'm most likely missing something.
Problem:
I'm using AJAX to send data using the POST method to a php file, the object is converted to json:

const body = {
  name: 'ilya',
  email: '[email protected]'
}

let xhr = new XMLHttpRequest();
xhr.open('POST', 'newtest.php');
xhr.responseType = 'json';
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify(body))


It seems like the data is being transferred:
6009dd5773a9f531663899.png
But I can't accept them in newtest.php in any way. This:
<?php
$input = json_decode(file_get_contents("php://input"), true);
  print_r($input);
?>

produces null.
Just accepting through the post also does not work.
Please, if possible, explain in detail to the ax where I'm screwing up, maybe it's impossible at all?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nadim Zakirov, 2021-01-22
@ilyabond

Do like this:

async function sendPOST() {
  
  try {
    
    var formData = new FormData();
    formData.append('name', 'Илья');
    formData.append('email', '[email protected]');

    var response = await (await fetch('newtest.php', {
      method: 'POST',
      body: formData
    })).text();

    console.log("POST-запрос отправлен успешно. Ответ сервера:\n" + response);

    return response;
    
  }
  
  catch (err) {
    
    console.log('При отправке POST-запроса произошла ошибка:');
    console.dir(err);
    
    return false;
    
  }
  
}

To send a request, you call the function sendPOST()
Inside the PHP handler, while looking at the $_POST global variable like this:
<?php
print_r($_POST);
?>

V
Vladislav, 2021-01-22
@Vladusik2

Try to set a negative offset for the test, so that the file is read from the end of the stream. And you must first simply display through var_dump what comes in file_get_contents

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question