简体   繁体   中英

Saving data into a text file sent as JSON with Ajax

I have currently a problem with my code. I would like to send JSON data with Ajax to a PHP script but it doesn't work. What does work is that the PHP script can be called by the Ajax code but it can't put the code into the .txt file. I have tried several things but I can't get it working. (I am trying to set the users array in the .txt file)

jQuery code:

          var users = [];              

          $.ajax({
              type: "POST",
              url: hostURL + "sendto.php",
              dataType: 'json',
              data: { json: JSON.stringify(users) },
              success: function (data) {
                  alert(data);
              }
          });

PHP Code:

<?php
$json = $_POST['json'];
$data = json_decode($json);

$file = fopen('test.txt','w+');
fwrite($file, $data);
fclose($file);

echo 'Success?';
?>

You must know that in PHP json_decode generates an Array that you can't write into an text file.

So only remove the json_decode command.

Since json_decode() function returns an array, you can use file_put_contents() that will save each array element on its own line

<?php
  $json = $_POST['json'];
  $data = json_decode($json, true);

  file_put_contents('test.txt',implode("\n", $data));
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM