1

I'm having trouble loading the objects of my JSON call into a client side sql db.

In my specific case, I have 3 objects that are returned from "jQuery.getJSON" and want to insert the value of the "content" key into the client-side web database such that my db contains the following:

id content
 1 "Text A"
 2 "Text B"
 3 "Text C"

The problem, however, is that my "for" loop cycles through all the returned JSON objects before beginning the execution of the db transaction. As a result, I end up with the following in my db:

id content
 1 "Text C"
 2 "Text C"
 3 "Text C"

Here's the code:

    jQuery.getJSON( url, params, function(obj, status, xhr){
      $('#myMessageCount').html(obj.length);
      var dbTable = 'messages';
      var jsObject = null;
      for (var i=0; i < obj.length; i++) 
      {
        jsObject = obj[i].message.content;
        db.transaction(function (tx) {
          tx.executeSql('INSERT INTO ' 
            + dbTable 
            + ' (content) VALUES (?)'
            , [jsObject], successHandler, errorHandler);
        });
       }
    });

Perhaps I need to do something with the JSON objects before trying to insert in the db? Hopefully, it's just some syntax that I'm overseeing. Any help is greatly appreciated!

Vee
  • 1,821
  • 3
  • 36
  • 60

1 Answers1

3

Unless you need to get to the JSON data somehow on the server, many just save it as a text blob and consume it on the client as-is without any conversion.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • Thanks, Diodeus. Your answer inspired me to try saving jsObject as a localStorage entry; however, the value saved in the db was "[object Object], [object Object], [object Object]". Can you give me some more direction? I'm assuming that I need to 1)convert my jsObject into a big long string, 2) save that string into the client db, and 3) parse that string for the values that I need. I'm pretty new at this stuff so apologies in advance for ignorant questions. – Vee Feb 06 '12 at 19:12
  • look at jquery's .serialize() to turn your data into a string. – Diodeus - James MacFarlane Feb 06 '12 at 19:28
  • Thanks, Diodeus. I used JSON.stringify for the conversion as referenced at http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery – Vee Feb 06 '12 at 19:49