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.
dataType: 'json',(don't forget: the capital T in dataType, enclose json in quotes, the trailing comma)Array (). Im starting to think its the way I set up mydetailsArraybut Im not sure what I've done wrong there.