2

I have a json file (file1.json) which contain json data. I would like to replace these data by new datas (newDataToStore).

I don't know how to do it using a php file (save.php file below) ?

Content of file1.json :

[
  {
    "key" : "test1",
    "desc": "desc1"
  },
  {
    "key" : "test2",
    "desc": "desc2"
  },
]

New json to write into json1.json file :

var newDataToStore = 
[
  {
    "key" : "test2",
    "desc": "desc2"
  },
  {
    "key" : "test3",
    "desc": "desc3"
  },
];

JS

this.save = function (newDataToStore) {
    jQuery.ajax({
        type : "POST",
        dataType : "json",
        url : 'save.php',
        data : newDataToStore,
        success : function() {
            console.log("SUCCESS");
        },
        error : function() {
            console.log("ERROR");
        }
   });
}
0

3 Answers 3

5

Another approach:

  1. You'll need to stringify the JS-Object before sending it to the server:

    this.save = function (newDataToStore) {
        jQuery.ajax({
            type : "POST",
            dataType : "json",
            url : 'save.php',
            data : {'json': JSON.stringify(newDataToStore)},
            success : function() {
                console.log("SUCCESS");
            },
            error : function() {
                console.log("ERROR");
            }
       });
    }
    
  2. On the serverside your script should do something like (as Mohammad Alabed pointed out):

    file_put_contents('/path/to/file1.json', $_POST['json']);
    

BUT, beware! Users could write arbitrary data to the file. You should always validate user input on the server side. (Maybe using a json schema)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, good piece of code but i get an exception : failed to open stream: Invalid argument on file_put_contents($_POST['json'], 'file1.json');
file_put_contents has a different order of attributes, sorry. I corrected it.
1

in php file the json data will be in the post global variable because you use post in your ajax

so all what you need is file_put_contents()

save.php

file_put_contents('file1.json', json_encode($_POST));

by using this function you will write a new json string to your json file (old content will be deleted)

Comments

0

in your save.php file

use json_decode()

it will decode your json datas passed from your ajax file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.