I am tearing my hair out of this one. I am only trying to teach myself php to do this one thing. Write a json file.
My php is probably a giant pile of dung, and more, was all over me with a 412 error. But moving it into the getJSON fixed that. My ajax call is somehow failing to feed the php my data, or my php function is not creating the file appropriately. Either way, I have an empty file
I wrote what was supposed to be an awesome proof of concept prototype, but as it is, the php portion or ajax call may be "made of fail". >__< Read on brethren, I wrote a simple demo.
I know it's silly to read a json file and then save a json file, but let me off on this technicality. Instead of having test.json, I have a servlet that gives me the json. I just save it in the javascript as javaobject. No sweat. But I tested it out as shown below:
demo.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Demo</title>
<script type= "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="test1.js"></script>
</head>
<body>
<h1>Test1</h1>
</body>
</html>
test.json
{"herp":1,"derp":2,"supersuper":3,"derpderp":5}
test.js
var newData;
$(document).ready(function()
{
$.getJSON('test.json', function(data)
{
console.log('test1.js');
console.log(data.herp);
console.log(data.derp);
console.log(data.supersuper);
console.log(data.derpderp);
//alert('success');
newData = data;
console.log(newData);
$.ajax({
type: 'POST',
url: 'json.php',
dataType: 'json',
data: {"json":newData},
data: {"json":JSON.stringify(newData)},
success: function()
{
alert('Successful submission');
},
error: function(e)
{
alert("error" + e);
console.log(this,arguments);
}
});
});
});
json.php
<?php
$json = $_POST['json'];
$file = fopen('new_data.json', 'w+');
fwrite($file, $json);
fclose($file);
?>
I am running this on apache httpd. For example, I just fire up localhost/demo.html on chrome and I read the diagnostics. No matter what I do, new_data.json is empty. I even tried to just call the php file and have it write a file. No post. It didn't do anything. No matter what, when I check the apache server (or anywhere for that matter), there is no data being written to new_data.json. It's just not there.
[EDIT] I added in the ability to print an error message. There is something wrong with the php. It is returning an error and I am not quite sure what is going on, here is the message I am currently studying:
Object {url: "json.php", type: "POST", isLocal: false, global: true, processData: true…}[Object, "parsererror", SyntaxError]
Please, can someone tell me what the heck I am doing wrong? I have stared at this for hours. I am willing to give rep, and if need be, take a ding on my own reputation on this, but I wouldn't ask unless I got desperate.
References PHP to file, JSON Post to file, Searched Overflow, and RTM