0

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

Community
  • 1
  • 1
Roy Grubb
  • 93
  • 2
  • 11

2 Answers2

3

You can't convert DOM elements to JSON.

Instead, you should save the HTML source.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

It turned out I wanted what outerHTML produces, but many thanks to @SLacks for the pointers which overcame my barrier to progress. Then I struggled with unwanted embedded backslashes that made the json invalid - a problem that is widely addressed in stackoverflow, but many of the answers didn't work for me until I found one mentioning stripslashes(), which did. My code now produces json that JSONLint finds valid. Next I have to find out how to read the JSON back and use it.

So here's my eventual solution to the original problem:

<!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" : [] };
                var allUserItems = $("p"); 
                for ( var index = 0; index < allUserItems.length; index++) {
                    jsonObject.userItem[index] = allUserItems[index].outerHTML;
                };
                // some jQuery to write to file
                $.ajax( {
                    type : "POST",
                    url : "json2.php",
                    data : { json : JSON.stringify(jsonObject) },
                    success: function () {console.log("Good!"); },
                    failure: function() {console.log("Error!");}
                });
            });
        </script>

        <title>Action list</title>
    </head>
    <body>
        <div id="inputs" class="pontano">
            <form name="checkListForm">
                <input type="text" name="checkListItem" style="width: 772px; height:25px"/>
            </form>
        </div>
        <div id="list">
            <p class='heading'>Head 1</p>
            <p class='item'>Item 1</p>
            <p class='item'>Item 2</p>
            <p class='item'>Item 3</p>
            <p class='heading'>Head 2</p>
            <p class='item'>Item 1</p>
            <p class='item'>Item 2</p>
            <p class='heading'>Head 3</p>
            <p class='item'>Item 1</p>
            <p class='item'>Item 2</p>
        </div>
    </body>
    <!-- ui-icon-arrowthick-2-n-s -->
</html>

The PHP (json2.php)

<?php
    $json = $_POST['json'];
    if (get_magic_quotes_gpc()) $json = stripslashes($json);       

    $file = fopen('todo2.json','w+');
    fwrite($file, $json);
    fclose($file);
?>

Which gives this in todo2.json

{"userItem":["<p class=\"heading\">Head 1</p>","<p class=\"item\">Item 1</p>","<p class=\"item\">Item 2</p>","<p class=\"item\">Item 3</p>","<p class=\"heading\">Head 2</p>","<p class=\"item\">Item 1</p>","<p class=\"item\">Item 2</p>","<p class=\"heading\">Head 3</p>","<p class=\"item\">Item 1</p>","<p class=\"item\">Item 2</p>"]}

I suspect that the stripslashes may be a kluge and if I did something different in the jQuery code, it might not be needed, but long experimenting didn't produce any other successful approach.

Roy Grubb
  • 93
  • 2
  • 11
  • From another question elsewhere, I learned that if (get_magic_quotes_gpc()) $json = stripslashes($json); Is better than what I had, which was $json = stripslashes($json); so I changed the PHP code accordingly. – Roy Grubb Jun 26 '14 at 14:14