I'm trying to learn how to use jQuery to store data in a .json file on my (LAN) server. Trouble is, the code writes an empty .json file and can't see why. I've referred to several answers in Stackoverflow and derived most of my code from those, (e.g. writing JSON object to .json file on server) but none quite solve the problem I'm facing, which is the processing of all elements in a jQuery wrapped set of .p
I've got the main code, which is not included, working - which is to allow a user to add paragraphs, and move them around by dragging. But I now have to write them to the server for the user to recall and work on later.
Here's the html:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="todo.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script>
$("document").ready(function() {
var jsonObject = { "userItem" : [] };
for ( var index = 0; index < $("p").length; index++) {
jsonObject.userItem[index] = $(".p[index]");
console.log(index);
console.log(jsonObject.userItem[index]);
};
// some jQuery to write to file
$.ajax( {
type : "POST",
processData : false,
url : "json.php",
dataType : 'json',
data : { json : jsonObject }
});
});
</script>
<title>To JSON</title>
</head>
<body>
<div id="list">
<p>Item 1</p>
<p>Item 2</p>
<p>Item 3</p>
</div>
</body>
</html>
and here's the php:
<?php
$myFile = "general.json";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_POST["data"];
fwrite($fh, $stringData);
fclose($fh)
?>
I suspect the problem is in this line:
jsonObject.userItem[index] = $(".p[index]");
I tried
jsonObject.userItem[index] = JSON.stringify($(".p[index]"));
but that gave me a "Converting circular structure to JSON" message, and I couldn't see why.
I'm fumbling here and would be grateful for any help.
Thanks, Roy