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!

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
look at jquery's .serialize() to turn your data into a string.
Thanks, Diodeus. I used JSON.stringify for the conversion as referenced at stackoverflow.com/questions/191881/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.