First of all, I apologize if this question sounds similar to others. I've done a lot of research and I guess I can't piece together my situation and issues other people have with this API.
I am creating an chrome app that basically demonstrates the ability to store and retrieve data from the Chrome Storage API. Once I'm comfortable doing this, I can implement this in a larger application I'm making.
However, I can't seem to get the basic app working. Here's the relevant code:
"storage.js"
function Store(key,data) {
console.log("Data: " + data);
chrome.storage.local.set({ key: data }, function () {
console.log("Secret Message Saved!");
});
}
function Retrieve() {
chrome.storage.local.get(function (data) {
console.log("The data stored is:" + data);
});
}
"master.js" (main script)
var myKey = "secretMessage";
var myData = "Pssst!";
Store(myKey, myData);
Retrieve(myKey);
console.log("Done!");
I'm at a loss. The output I get is:
Data: Pssst!
Done!
Secret Message Saved!
The data stored is:[object Object]
It appears that either I'm storing wrong or retrieving wrong.
I've looked through the documentation. Maybe I'm just not understanding the concept of the API and what it is able to store and retrieve. I'm fairly new to coding in the javascript language. Any help would be much appreciated!
Thanks!
First,
chrome.storage.local.set & chrome.storage.local.get
are asynchronous methods, you have to wait till chrome.storage.local.set stores data in storage, then you should call chrome.storage.local.get.
Second,
chrome.storage.local.get is returning an object. You can view object by using .toString() or JSON.stringify(data)
function Store(key,data, callback) {
console.log("Data: " + data);
chrome.storage.local.set({ key: data }, function () {
console.log("Secret Message Saved!");
callback(true);
});
}
function Retrieve(success) {
chrome.storage.local.get(function (data) {
console.log("The data stored is:" + JSON.stringify(data));
});
}
var myKey = "secretMessage";
var myData = "Pssst!";
Store(myKey, myData, Retrieve);
console.log("Done!");
I've used this callback method without a problem.
function loadSelectedStyle(){
chrome.storage.local.get('defaultColorSet', function (result) {
console.log(result.defaultColorSet);
defaultColors(result.defaultColorSet);
});
}
If you just write 'result' to the console log, you can see the entire object, by adding the key to result you get the data.
Related
I'm trying to send a "large" table in OfficeJS:
functionfile.html loaded from manifest route
<script>
(function (){
"use strict";
Office.initialize = function (reason) {
$(document).ready(function() {
$("#send-data-button").click(send_data);
});
};
function send_data() {
return Excel.run( function(context) {
var data = context.workbook.worksheets.getItem("SheetName")
.getRange("A1:K3673").load("values");
return context.sync().then( function() {
// 2d table is correctly seen
// $("body").append(data.values);
// Just gets lost in ajax call
$.ajax({
type: "GET",
url: mysite,
data: {"accessData": data.values},
}).done( function(success) {
$("body").append("All Done");
}).fail( function(error) {
$("body").append("Error == " + JSON.stringify(error));
});
return context.sync();
});
});
}
})();
</script>
<div> <button id="send-data-button"> Send </button></div>
However i'm not sure how to send this, on the backside I have a flask server catching the request and was hoping I could just use pandas.read_json but no matter how I try to send this i'm getting different errors. Here's the printout of flask.request when data.values[0][0]:
CombinedMultiDict([ImmutableMultiDict([('update_date', '43191'), ('accessData', 'Channel')]), ImmutableMultiDict([])])
And when I try data.values[0] I get a list of values, which is what i'd expect
CombinedMultiDict([ImmutableMultiDict([('update_date', '43191'), ('accessData[]', 'Channel'), ... <All my column headers>, ImmutableMultiDict([])])
But when I try to send the 2D array with just data.values I get an error message in ajax.fail:
Error == {"readyState":0,"status":0,"statusText":"error"}
I also tried JSON.stringify(data.values) and got the same error message:
Error == {"readyState":0,"status":0,"statusText":"error"}
I even tried to take each column and convert them to some kind of list as nested keys inside accessData but I was getting the same error message. Any help would be greatly appreciated.
Ideally, you should isolate the getting-data-from-Excel part from your ajax call part. Right now, the two are intertwined, which makes it both harder to help debug, and just conceptually less clean.
For the Excel part, you should be able to do:
function getExcelData(){
return Excel.run( function(context) {
var data = context.workbook.worksheets.getItem("SheetName")
.getRange("A1:K3673").load("values");
return context.sync()
.then(function() {
return data.values;
});
})
}
This will free you up to then do:
getExcelData().then(function(values) {
$.ajax(...)
});
Note that range.values returns just a regular 2D array, nothing special. So you can try out your ajax call independently of the Excel call (which is yet another reason to separate those out)
I am kind of struggling with my JavaScript. Still getting my head around the callbacks. I have a function which recursively fetches the next link page from an REST endpoint.which works fine for a single url
Now i need to use the same recrusive function to do same for other end points. thats where iam struggling now. It is obvious that iam missing a point or i badly understood callback concept.
please excuse the formatting What i have done so far ..
function getFullLoad(rest_url,callback){
mongoose.connect(url, function(err) {
console.log(url);
if (err) throw err;
console.log("successfully connected");
getToken(function(err, token) {
if (err) throw console.error(err);
console.log('using access token to retrieve data :', token[0]
['access_token']);
var options = {
'auth': {
'bearer': token[0]['access_token']
}
}
request.get(rest_url, options, function(error, response, body) {
if (!error && response.statusCode === 200) {
var data = JSON.parse(body);
//save data in mongo
});
}
var next_page = JSON.parse(body)["_links"]["next"]
if (next_page) {
var next_page_url = JSON.parse(body)["_links"]["next"]["href"];
console.log("Fetching data from ", next_page);
//recrusively call back with next url
getFullLoad(next_page_url,callback);
} else {
callback();
} else {
if (error) throw error;
}
});
rest_url= "http://myrest_url"
//this bit is working if there is a single url
getFullLoad(rest_url, function() {
console.log('done , got all data');
});
this works great ,now i need to call the same function with different urls . It may be some urls may not have not pagination.
so far this is my effort , it only takes the first url and then does nothing.
This bit is not working . what iam doing wrong? i tried creating another callback function. i guess my knowledge is quite limited on callbacks. any help very much appreciated
api_endpoints =[ {"url1": "http://url1"},{"url2": "http://url2"}]
api_endpoints.forEach(function(Item, endpoint) {
var endpoint_name = Object.keys(api_endpoints[endpoint]).toString());
var rest_url = api_config.BASE_URL + api_endpoints[endpoint]
[endpoint_name];
getFullLoad(rest_url, function) {
console.log('done');
});
});
Thank you for looking my question
With a bit of refactoring I think you can get something to work.
I would change your getFullLoad method to return a promise (the request.get) then in your foreach loop I would build up an array of promises that call the getFullLoad with the different urls.
Then use promises.all(arrayOfPromises) to execute them and manage the results.
It will be easier to understand and maintain long term.
Check out the promise documentation here:
Promise.all
I am trying to make a model (the M in MVC) in my web application, to understand the concept. I am struggling with the async problem that occurs in my code below:
function FruitModel(api) {
this._api = api;
}
FruitModel.prototype = {
getFruit: function(fruit_id) {
$.getJSON(this._api + fruit_id, function(data){
return data;
});
}
}
$(function(){
var fruits = new FruitModel("/fruit/");
console.log(fruits.getFruit(123))
});
I get that this is wrong because the console.log will happen before the getJSON has finished, be cause of that this is asynchronous. How should I design this instead to prevent the problem?
I suppose that getting the actual data for a front end MVC is to access it from within the model from a RESTapi equal to mine. Is there a preferred solution instead of doing this inside the model as I do?
You can send a callback to the function and execute it when you done with your async code:
FruitModel.prototype = {
getFruit: function(fruit_id,callback) {
$.getJSON(this._api + fruit_id, function(data){
callback(data);
});
}
}
$(function(){
var fruits = new FruitModel("/fruit/");
fruits.getFruit(123, function(data){
console.log(data);
});
});
To avoid that problem you can do something like this ( because from jQuery 1.5 .getJSON implements Promise interface )
function FruitModel(api) {
this._api = api;
}
FruitModel.prototype = {
getFruit: function(fruit_id) {
return $.getJSON(this._api + fruit_id);
}
}
//Call
fruits.getFruit(123).done(function(data){
console.log(data);
})
Okay, so today I was adding a new feature to my chat thing and I wanted it to whenever an admin typed /clearchat, it would clear the chat.
But then there is this weird bug that when I run getAllMessages(), it returns undefined. I tried printing the value it returns in the function, and that had a value!
Following is the code:
function getAllMessages() {
var Chat = Parse.Object.extend("message");
var query = new Parse.Query(Chat);
query.find({
success: function(message) {
console.log(message);
return message;
},
error: function(message, error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
If you want to actually test it out, I edited the code a little and put it on JSFiddle (Click here).
(Of course, I made a new Parse project so my data wouldn't get hacked)
Any help would be highly appreciated!
Thanks,
Oliver
Ohhhhh
The query.find() function was asynchronous! So it was undefined at that time!
I have been trying for hours to read the table from within azure client services with absolutely no success...
I can insert items into the table fine, but when reading from the table it doesnt even seem to do the where part, I feel like i have tried every different version of code to get this working but nothing is working for me :(
console.log("user_id1" + user_id1)
notpic_pushClient.getTable("myTable").where({
user_id: user_id1
}).read({
success: function (results) {
if (results.length > 0) {
console.log("yes exists");
} else {
console.log("no doesnt exist yet");
}
}
});
This doesnt work BUT the code below does....I am baffled...do I need something special in the read section of scripts on that table?
var item = { user_id: user_id1, text: "New User Added" };
notpic_pushClient.getTable("myTable").insert(item);
EDIT
I have just read another post Azure mobile services: basic read function in javascript that explains success is for server side and done is for client side so tried
var client = new WindowsAzure.MobileServiceClient('https://mydemo.azure-mobile.net/', 'xxxxxxxxxxxxRxxxxxxxxxxxxxxxxxxxxx');
usersTable = client.getTable("myTable");
usersTable.where({ user_id: user_id1 })
.read()
.done(
function (results) {
console.log("results: " + results)
try {
console.log("exists")
}
catch(err) {
console.log("doesnt exist yet")
}
}
);
BUT this still wont work, nothing gets logged to the console, I am using visual studio and dont even know if it is sending the request?
In the client side, it's possible that there is an error returned in the done promise, but you're not doing anything with it. Try rewriting your code as shown below, and if there are errors you'll see them.
var client = new WindowsAzure.MobileServiceClient('https://mydemo.azure-mobile.net/', 'xxxxxxxxxxxxRxxxxxxxxxxxxxxxxxxxxx');
usersTable = client.getTable("myTable");
usersTable.where({ user_id: user_id1 })
.read()
.done(
function (results) {
console.log("results: " + JSON.stringify(results));
}, function (err) {
console.log("Errors: " + JSON.stringify(err));
}
);