Omega Collision
Omega Collision

Reputation: 125

Writing a JSON object to an existing .json file

EDIT: My error checking shows that the php is being executed but when I check my .json file it's still the same as before.

I apologize in advance since this has been asked before but I've spent hours trying out different things and none have worked. Hopefully this might help someone in a similar situation. I'm trying to append a new entry to my existing json object from user input and write the updated json object back to the file. The last part is what's giving me trouble.

Here I'm using ajax to send my json object to a php file

$.getJSON("http://existing.json", function(data){
    //append new entry to previous json array
    data['posts'].push(objectt);
    //confirming that new object is correct
    console.dir(data);
    //Sending json object to .php file so it can write to .json file
        $.ajax({
            type : "POST",
            url : "json.php",
            //data : data,    this was changed to 
            data : {json:data}, //by  the suggestion of suggested by madalin ivascu
            dataType: 'json'
        }); 

The above block of code executes and no errors are displayed in the console. Here is my json.php file. After the next block of code executes my .json file does not have the new entry.

 $json = $_POST['json'];

 if ($_POST['json'])
 {
   $file = fopen('simple.json','w+');
   fwrite($file, $json);
   fclose($file); 
   echo: "File was updated";
 }
 else
 {
   // user has posted invalid JSON, handle the error
      print "Error json was null";
 }

Upvotes: 1

Views: 188

Answers (1)

madalinivascu
madalinivascu

Reputation: 32354

Change data : {json:data},

Return something from the php

 $json = $_POST['json'];

 if (json_decode($json) != null)
 {
   $file = fopen('simple.json','w+');
   fwrite($file, $json);
   fclose($file); 
   echo "File updated";
 }
 else
 {
   // user has posted invalid JSON, handle the error
      print "Error json was null";
 }

Upvotes: 3

Related Questions