Reputation: 402
I am trying to store json data returned by the $.ajax() function, but am having trouble. Below is the call I make (which I know returns my JSON data properly, I have logged it (url removed for personal reasons).
$.ajax({
type: "GET",
url: **url that returns json data**
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
return msg;
},
error: function(e){
WL.Logger.log(e);
}
});
And then I initialize my JSONStore using worklight:
//Setup JSON store
var collectionName = 'people';
//Object that defines all the collections
var collections = {};
//Object that defines the 'people' collection
collections[collectionName] = {};
WL.JSONStore.init(collections);
So now here is where I am having my issue. I want to add the JSON data I am returning from my ajax call to my JSONStore. So I have attempted this (getJSONData is a wrapper around the ajax call above):
WL.JSONStore.get(collectionName).add(getJSONData());
However, when I print the collection, nothing is stored in it, and when I print WL.JSONStore.get(collectionName).count, nothing is returned. How can I add the data returned to me properly?
Upvotes: 0
Views: 449
Reputation: 1225
Both the AJAX call and the JSONStore APIs are asynchronous APIs, meaning that you either have to use the deferred returned by them, or pass a success callback to be able to wait for it to finish before going to the next step.
The reason you get the PERSISTENT_STORE_NOT_OPEN is that you are calling init and instead of waiting for it to finish, you immediately call add without init being done, which is why it says the store has not been initialized.
You would probably do something like this:
$.ajax({
type: "GET",
url: **url that returns json data**
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//Setup JSON store
var collectionName = 'people';
//Object that defines all the collections
var collections = {};
//Object that defines the 'people' collection
collections[collectionName] = {};
WL.JSONStore.init(collections)
.then(function(res){
WL.JSONStore.get(collectionName).add(getJSONData());
});
return msg;
},
error: function(e){
WL.Logger.log(e);
}
});
(Note how I changed the success callback to use the result of the AJAX call.)
Edit: Here is some more information on deferreds and promises in Javascript for reference: http://code.tutsplus.com/tutorials/wrangle-async-tasks-with-jquery-promises--net-24135
JSONStore returns a promise with every API call so that you can use the promises for handling callbacks instead of having to pass a success and failure callback everytime.
Upvotes: 2
Reputation: 2698
The call you are making above is asynchronous. So its probably not returning what you think it is.
You would either have to:
Upvotes: 1