0

What I'm trying to do is the following: I want to send a JSON object from my jQuery code to the PHP file on my server. I want the PHP file to append this JSON object to my text file.

The problem:

I'm struggeling with the PHP file. I'm sending the data and I need the PHP to save that data in a variable so that I can write it into a textfile. The problem is that it doesn't do that. The post I make, apparently, has no content (it just shows array()).

My jQuery code:

var username = "";
var password = "";
var url = window.location.href;
var title = document.title;
var detailsArray = {title : [{
                    "title" : title,
                    "url" : url, 
                    "username" : username, 
                    "password" : password
                    }]
                    };

$(document).keydown(function(e) {
    if(e.which == 17) {
        console.log(detailsArray);
        $.ajax({
          type: "POST",
          url: "http://......./Server.php",
          data: detailsArray,
          success: function(data) {
              console.log("Data sent!"+data);
          }
        });
    }
});

My PHP code:

$dataToBeInserted = $_POST;
$file = "JSON.json";

//Open the file with read/write permission or show text
$fh = fopen($file, 'a+') or die("can't open file");
$stat = fstat($fh);

//Remove the last 2 characters from the JSON file
ftruncate($fh, $stat['size']-2);

//Add the data from $dataToBeInserted to the file
echo fwrite($file, $dataToBeInserted );

//Close the file
fclose($fh);

This PHP file gives a couple of warning/errors:

Array ( )

Warning: fwrite() expects parameter 1 to be resource, string given in Server.php on line 17

Warning: fwrite() expects parameter 1 to be resource, string given in Server.php on line 19

What am I doing wrong here? I'm not used to PHP so there's probably a bunch of errors in there, but I thought the jQuery side was okay.

4
  • 2
    Doesn't fwrite need $fh instead of file? php.net//manual/en/function.fwrite.php Commented Jun 6, 2014 at 18:06
  • In your ajax code block, try adding the option: dataType: 'json', (don't forget: the capital T in dataType, enclose json in quotes, the trailing comma) Commented Jun 6, 2014 at 18:18
  • @gibberish: I just tried that but it still gives the Array (). Im starting to think its the way I set up my detailsArray but Im not sure what I've done wrong there. Commented Jun 6, 2014 at 18:31
  • Scratch that, it must be something else. I just used the code xcezzz gave me and it's reading the JSON perfectly fine! This means I have something weird in my PHP file thats not supposed to be there, but I'll figure it out. Thank you for trying (and helping) :) Commented Jun 6, 2014 at 18:57

1 Answer 1

1

first your fwrite($file) should be fwrite($fh).. you have to write to the file handle returned by fopen... not the string name of the file.

$dataToBeInserted = $_POST;
$file = "JSON.json";

//Open the file with read/write permission or show text
$fh = fopen($file, 'a+') or die("can't open file");
$stat = fstat($fh);

//Remove the last 2 characters from the JSON file
ftruncate($fh, $stat['size']-2);

//Add the data from $dataToBeInserted to the file
echo fwrite($fh, $dataToBeInserted );

//Close the file
fclose($fh);

but then your JSON file is incomplete/corrupt. since you removed the 2 characters, but never added them back.

honestly the easy way to solve this would be

$data = json_decode(file_get_contents('JSON.json'));
if (!$data) $data = array();
array_push($data, $_POST);
file_put_contents('JSON.json', json_encode($data);

but this will get very expensive IO/resource wise the larger it gets

other method.... see comments

$dataToBeInserted = $_POST;
$file = "JSON.json";

//Open the file with read/write permission or show text
$fh = fopen($file, 'a+') or die("can't open file");
$stat = fstat($fh);

//Remove the last 2 characters from the JSON file
//ftruncate($fh, $stat['size']-2);

//Add the data from $dataToBeInserted to the file with a comma before it if there is data in file already.
if ($stat['size'] != 0) $append = ",";
echo fwrite($fh, $append . json_encode($dataToBeInserted) );

//Close the file
fclose($fh);

now to read it..

$data = file_get_contents('JSON.json');
$dataArray = json_decode('[' . $data  . ']');

so now each time we write to the file we put a comma, then when we read it we wrap it in brackets so it's an array of the writes we have been doing.

While this wont be as resource intensive write-wise it will be read wise... but thats because you want everything in one file.

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

6 Comments

You were right about the error message, $file was supposed to be $fh. The resources will be a problem eventually because the JSON file will end up being very long. Is there a (less) easy to do this?
That comes down to how will this data be used/loaded? Can you just dump each request to an individual file in a directory based off timestamp or date("Y-m-dH-i-s") type format? then there is no resource issue on a big ol file, but then how will the data be read back?
I'm afraid not, it has to be in a single file. I'll eventually be doing things with Arduino, which has VERY limited resources.
well reading in a big ol file will still be a problem on that kind of platform... but I will update the answer with another way if you have control over the way it is read...
hope that all makes sense... this way it's mostly valid JSON in the file and just needs a bracket burrito to be read properly
|

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.