0

This is the JSON file that I use:

    {
        "dat": [
            {
                "name": "Bill",
                "age": 20
            }
        ]
    }

This is the actual source (dumbed down to show only the bug) that I use. So feel free to past this into an HTML file and tinker.

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    </head>
    <body>
    <div id="out"></div>
    <script type="text/javascript">

    /******************
     * Global Variables
     ******************/
    var counter = 1;  //Used to track users movement 
    var json;


    Storage.prototype.setObject = function(key, value) {
        this.setItem(key, JSON.stringify(value));
    }

    Storage.prototype.getObject = function(key) {
        var value = this.getItem(key);
        return value && JSON.parse(value);
    }


    function load(location, storageName)
    {
       $.ajax({
          url: location,
          dataType: "text",   //force to handle it as text
          success: function(data)
          {
            localStorage.setObject(storageName, JSON.parse(data));
          }
        })
    };

    /****************************
     * Pushes any content updates to the user.
     ****************************/

    function populate(Number)
    {
      $.each(json.dat, (function(key, value) 
        {
           $('#out').html('Name: ' + value.name + '<br> Age: ' + value.age);
        }))
    }


    /********************************
     * The main program
     ********************************/

    $(document).ready(function(){
     load('work.json', 'jsoncache');
     json = localStorage.getObject('jsoncache');
     populate(counter);

    })
    </script>
    </body>
    </html>

The problem that I am having is that the first time the app is loaded, it throws an error in the console. The second time that you load it (just hit refresh) it works perfectly fine.

I found this problem while changing data and refreshing. If i changed the data and refreshed, the localStorage would load and update the data, but the text displayed on the screen would be the same. Hit refresh again, and the text on screen will show the new data (that was loaded the last time the page was refreshed).

Another thing I have found is that if you run the app without having the localStorage already existing, it throws a different error. Anyone know anything about that?

I am not sure if it is a bug in my code or an issue with the browser. Any thoughts?

flockerman
  • 15
  • 2
  • 1
    Your "load" function conducts an **asynchronous** operation. The function will return long before the data is actually received by the browser. – Pointy Mar 06 '14 at 20:19
  • also note localStorage stores strings so your `localStorage.setObject(storageName, JSON.parse(data));` is wrong should just be `localStorage.setObject(storageName, data);` – Patrick Evans Mar 06 '14 at 20:22

1 Answers1

1

You try to get the item from the localStorage before your AJAX requests returns, therefore, in the populate method, when you try to acces json.dat, you get an error, because json is undefined. But the second time, the asynchronous request has already stored the object, and so it works. Change your load function to:

function load(location, storageName)
{
   $.ajax({
      url: location,
      dataType: "text",   //force to handle it as text
      success: function(data)
      {
        json = JSON.parse(data); //Why don't you use 'json' dataType directly?
        localStorage.setObject(storageName, json);
        populate(counter);
      }
    })
};

And remove from the ready() method everything after your load() call (or check for errors)

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42