Alex Shaw
Alex Shaw

Reputation: 169

Save to server side file from PHP via Javascript

I am trying to save a json string from a javascript file to a local file on the server using PHP, however, my json file is not being modified at all. Here is my Javascript:

function saveToFile(data){
  jsonString = JSON.stringify(data);
  $.ajax({
    url: 'php/save.php',
    data : jsonString,
    type: 'POST'
  });
}

Note that jsonString is a valid variable, and i can log it correctly into the console.

Here is my PHP:

<?php
  $data = $_POST['jsonString'];
  $f = fopen("../website-contents.json", "w") or die("fopen failed");
  fwrite($f, $data) or die("fwrite failed");
  fclose($f);
?>

Note that even tests trying to save "Hello World" to "test.txt" don't work, or through errors.

Finally, here is my folder structure: enter image description here

Upvotes: 1

Views: 7251

Answers (2)

Pratik Soni
Pratik Soni

Reputation: 2588

Here is your solution.

Js code

function saveToFile(data){
  jsonString = JSON.stringify(data);
  $.ajax({
    url: 'php/save.php',
    data : {'jsonString':jsonString},
    type: 'POST'
  });
}

php code.

$data = $_POST['jsonString'];
//set mode of file to writable.
chmod("../website-contents.json",0777);
$f = fopen("../website-contents.json", "w+") or die("fopen failed");
fwrite($f, $data);
fclose($f);

Upvotes: 8

davidkonrad
davidkonrad

Reputation: 85528

I agree with the comments pointing out you must have a permission problem. However, it will not work after you have corrected this problem either. You have

$data = $_POST['jsonString'];

but where do you set a key called jsonString? Use

function saveToFile(data){
  var jsonString = JSON.stringify(data);
  $.post("php/save.php", {
     jsonString: jsonString
  })
}

instead.

Upvotes: 1

Related Questions