Vee
Vee

Reputation: 1841

Inserting JSON objects into client-side web sql db

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!

Upvotes: 1

Views: 3459

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

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.

Upvotes: 3

Related Questions