HTTPPost for JSON in PHP

I am making an HTTP message request in Javascript to update a JSON file.

function updateJson(dataNew){
  var stringData = JSON.stringify(dataNew);
    $.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: 'update.php',
    data: {stringData},
    success : function(d){
       alert('done');}
    })
}

Then in PHP:

<?php
  $a = json_encode(file_get_contents("php://input"));
  file_put_contents('newData.json', $a);
?>

I want JSON data in a JSON file, however the json file contains only one line, similar to the payload of an http message message. What am I doing wrong?

+4
source share
1 answer

I would suggest passing the key / value pair in the data object and leaving the contentType attribute by default (delete it), for example:

$.ajax({
    ...
    data: {myjson: stringData},
    ...
);

Then in PHP you have to read the published data and get this myjson element without encoding it again, since it is already JSON:

<?php
  $a = $_POST['myjson'];
  file_put_contents('newData.json', $a);        
?>
+3
source

Source: https://habr.com/ru/post/1620919/


All Articles