failed to send array in url in workligh application using jquerymobile - jquery-mobile

I am building a hybrid application in IBM worklight using jquerymobile.
I want to send the json array returned by server php to another page in the url. The codes are shown below:
searchPools.js file
(file from which the another page is called)
$(document).undelegate('#srhPool', 'click').delegate('#srhPool', 'click', function() {
var source = $("#csource1").val();
var destination = $("#cdest1").val();
var poolDate = $("#pooldate1").val();
if(source == null || source == "")
$("#csource1").parent().css('border','2px solid red');
if(destination == null || destination == "")
$("#cdest1").parent().css('border','2px solid red');
if(poolDate == null || poolDate == "")
$("#pooldate1").parent().css('border','2px solid red');
if(source == null || source == "" || destination == null || destination == "" || poolDate == null || poolDate == "" || validateRadio == false){
alert("Oops! Your Pooling Info is Incomplete.");
}
else{
savePool(userId, source, destination, poolDate, preferVehicle);
}
});
//save pool info
function savePool(userId, source, destination, poolDate, preferVehicle){
$.mobile.utils.showWaitBox("a", "Wait! Searching Poolers...");
var invocationData9 = {
adapter : 'registerUser',
procedure : 'searchPoolData',
parameters : [userId, source, destination, poolDate, preferVehicle]
};
WL.Client.invokeProcedure(invocationData9, {
onSuccess : poolSuccess,
onFailure : poolFailure,
});
}
function poolSuccess(result){
$.mobile.utils.hideWaitBox();
var invocationResult = result.invocationResult;
var array1 = invocationResult.pools;
var dataurl2 = '?array='+array1;
$.mobile.changePage('../../pages/passenger/poolResults.html'+dataurl2, {transition: "slide"});
}
function poolFailure(result){
$.mobile.utils.hideWaitBox();
WL.Logger.error('Search Unsuccessful');
}
poolResults.js(the file where the array is accessed)
$(document).on( 'pagebeforeshow', '#poolResults', function(event){
var params = new Array();
function getParams(){
var idx = document.URL.indexOf('?');
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
getArray = unescape(params["array"]);
alert(getArray);
});
Its not working. What I want to do is that I clicked a button in a page, then some results are retreived through http adapters. In the searchPools.js file, the values are successfully obtained in the poolSuccess function. Now, these values are to be displayed on the other page which is showed using $.mobile.changePage. I want to know the way I am using is right, or some other way is available for achieving this.

Send the array like this
$.mobile.changePage('page2.html', { dataUrl : "page2.html?parameter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });
and retrive them like
$("#index").live('pagebeforeshow', function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
For More Info See The Link
For your understanding Pass it as
$.mobile.changePage("newPage.html", {data:{ param1 : YOUR JSON } });
And retrive it as
<script type="text/javascript">
$("#newPageId").on("pageshow", onPageShow);
function onPageShow(e,data)
{
var url = $.url(document.location);
var param1 = url.param("param1");
}
</script>

Related

Why I cannot using cookies variable value outside the cookie.get function?

I just began to learning using electron.
I have set a cookie and I want using it value.
function getCookie(cname) {
var value = {
name: cname
};
session.defaultSession.cookies.get(value, function (error, cookies) {
let cookieStr = ''
for (var i = 0; i < cookies.length; i++) {
let info = cookies[i];
cookieStr += `${info.name}=${info.value};`;
console.log(info.value, info.name);
let somevalue = info.value;
}
console.log(cookieStr);
alert(somevalue); //alert 1
});
alert(somevalue); //alert 2
}
</script>
I got the cookieStr value in console.log.
Then in somewhere place, I want to use cookieStr value by calling getcookie(cname) but it keep undefined. How to use the cookie value outside the function?
I have tried display the value with 'alert 1' inside the cookie.get function and it is work. But, the 'alert 2' which outside cookie.get function keep displaying undefined.
Thank you
Reading cookies in electron is an asynchronous function. So its better to call the the function with a callback to return value. or else promisify the function.
function getCookie(cname,callback) {
var value = {
name: cname
};
session.defaultSession.cookies.get(value, function (error, cookies) {
let cookieStr = ''
for (var i = 0; i < cookies.length; i++) {
let info = cookies[i];
cookieStr += `${info.name}=${info.value};`;
console.log(info.value, info.name);
let somevalue = info.value;
}
callback(cookieStr);
});
//alert(somevalue); //alert 2
}
getCookie('test',function(returnValue){
//use the return value here
})

How to create batch using oData in SAPUI5 but I am able to create single record each time

I am not able to send batch records. But I am able to add single entity each time. I used the following function on submit.
// creating single entry each time.
onSubmitChanges: function() {
var oSelectedVal = this.getView().byId("plmSelect"),
oSelectedVal = oSelectedVal.getSelectedItem().getKey(),
oModel = this.getView().getModel(),
oEntry = {};
oEntry.MyKeyField1 = oSelectedVal;
oEntry.MyEntry1 = globalVariable1; // global variable declared to get values
oEntry.MyEntry2 = globalVariable2;
oEntry.MyEntry3 = globalVariable3;
oEntry.MyEntry4 = globalVariable4;
if (oEntry.MyKeyField1 !== "" && oEntry.MyEntry1 !== "" && oEntry.MyEntry2 !== "") {
var oContext = oModel.createEntry('/MyEntitySet', {
properties: oEntry,
success: function() {
MessageToast.show("Create successfuly");
// not able to delete/remove after created successfully used the following
//oModel.setBindingContext(oContext);
//oModel.resetChanges();
//aModel.destroyBindingContext();
/*oModel.updateBindings({
bForceUpdate: true
});*/
// oModel.refresh();
//oModel.deleteCreatedEntry();
},
error: function() {
MessageToast.show("Create failed");
}
});
oModel.submitChanges();
//oModel.refresh();
} else {
MessageToast.show("Store Area and Store Description are madatory.");
}
this.onUpdateFinished();
},
Batch is not allowed. You must use deep entity if you wanna send a table.

Google docs spreadsheet script error OAuthConfig when fetching data from Fitbit

I have got following script in Google docs spreadsheet which is fetching data from Fitbit. Script worked fine so far but recently on 6th July Google stopped using OAuthConfig so script is not working since:-(
I am not programmer, I am just advanced user. So I would like to kindly ask some programmer to help tune script below in order to make it work again.
// Key of ScriptProperty for Firtbit consumer key.
var CONSUMER_KEY_PROPERTY_NAME = "fitbitConsumerKey";
// Key of ScriptProperty for Fitbit consumer secret.
var CONSUMER_SECRET_PROPERTY_NAME = "fitbitConsumerSecret";
// Default loggable resources (from Fitbit API docs).
var LOGGABLES = ["activities/log/steps", "activities/log/distance",
"activities/log/activeScore", "activities/log/activityCalories",
"activities/log/calories", "foods/log/caloriesIn",
"activities/log/minutesSedentary",
"activities/log/minutesLightlyActive",
"activities/log/minutesFairlyActive",
"activities/log/minutesVeryActive", "sleep/timeInBed",
"sleep/minutesAsleep", "sleep/minutesAwake", "sleep/awakeningsCount",
"body/weight", "body/bmi", "body/fat",];
// function authorize() makes a call to the Fitbit API to fetch the user profile
function authorize() {
var oAuthConfig = UrlFetchApp.addOAuthService("fitbit");
oAuthConfig.setAccessTokenUrl("https://api.fitbit.com/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://api.fitbit.com/oauth/request_token");
oAuthConfig.setAuthorizationUrl("https://api.fitbit.com/oauth/authorize");
oAuthConfig.setConsumerKey(getConsumerKey());
oAuthConfig.setConsumerSecret(getConsumerSecret());
var options = {
"oAuthServiceName": "fitbit",
"oAuthUseToken": "always",
};
// get the profile to force authentication
Logger.log("Function authorize() is attempting a fetch...");
try {
var result = UrlFetchApp.fetch("https://api.fitbit.com/1/user/-/profile.json", options);
var o = Utilities.jsonParse(result.getContentText());
return o.user;
}
catch (exception) {
Logger.log(exception);
Browser.msgBox("Error attempting authorization");
return null;
}
}
// function setup accepts and stores the Consumer Key, Consumer Secret, firstDate, and list of Data Elements
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle("Setup Fitbit Download");
app.setStyleAttribute("padding", "10px");
var consumerKeyLabel = app.createLabel("Fitbit OAuth Consumer Key:*");
var consumerKey = app.createTextBox();
consumerKey.setName("consumerKey");
consumerKey.setWidth("100%");
consumerKey.setText(getConsumerKey());
var consumerSecretLabel = app.createLabel("Fitbit OAuth Consumer Secret:*");
var consumerSecret = app.createTextBox();
consumerSecret.setName("consumerSecret");
consumerSecret.setWidth("100%");
consumerSecret.setText(getConsumerSecret());
var firstDate = app.createTextBox().setId("firstDate").setName("firstDate");
firstDate.setName("firstDate");
firstDate.setWidth("100%");
firstDate.setText(getFirstDate());
// add listbox to select data elements
var loggables = app.createListBox(true).setId("loggables").setName(
"loggables");
loggables.setVisibleItemCount(4);
// add all possible elements (in array LOGGABLES)
var logIndex = 0;
for (var resource in LOGGABLES) {
loggables.addItem(LOGGABLES[resource]);
// check if this resource is in the getLoggables list
if (getLoggables().indexOf(LOGGABLES[resource]) > -1) {
// if so, pre-select it
loggables.setItemSelected(logIndex, true);
}
logIndex++;
}
// create the save handler and button
var saveHandler = app.createServerClickHandler("saveSetup");
var saveButton = app.createButton("Save Setup", saveHandler);
// put the controls in a grid
var listPanel = app.createGrid(6, 3);
listPanel.setWidget(1, 0, consumerKeyLabel);
listPanel.setWidget(1, 1, consumerKey);
listPanel.setWidget(2, 0, consumerSecretLabel);
listPanel.setWidget(2, 1, consumerSecret);
listPanel.setWidget(3, 0, app.createLabel(" * (obtain these at dev.fitbit.com)"));
listPanel.setWidget(4, 0, app.createLabel("Start Date for download (yyyy-mm-dd)"));
listPanel.setWidget(4, 1, firstDate);
listPanel.setWidget(5, 0, app.createLabel("Data Elements to download:"));
listPanel.setWidget(5, 1, loggables);
// Ensure that all controls in the grid are handled
saveHandler.addCallbackElement(listPanel);
// Build a FlowPanel, adding the grid and the save button
var dialogPanel = app.createFlowPanel();
dialogPanel.add(listPanel);
dialogPanel.add(saveButton);
app.add(dialogPanel);
doc.show(app);
}
// function sync() is called to download all desired data from Fitbit API to the spreadsheet
function sync() {
// if the user has never performed setup, do it now
if (!isConfigured()) {
setup();
return;
}
var user = authorize();
// Spatny kod, oprava nize - var doc = SpreadsheetApp.getActiveSpreadsheet();
var doc = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Pavel');
doc.setFrozenRows(1);
var options = {
"oAuthServiceName": "fitbit",
"oAuthUseToken": "always",
"method": "GET"
};
// prepare and format today's date, and a list of desired data elements
var dateString = formatToday();
var activities = getLoggables();
// for each data element, fetch a list beginning from the firstDate, ending with today
for (var activity in activities) {
var currentActivity = activities[activity];
try {
var result = UrlFetchApp.fetch("https://api.fitbit.com/1/user/-/"
+ currentActivity + "/date/" + getFirstDate() + "/"
+ dateString + ".json", options);
} catch (exception) {
Logger.log(exception);
Browser.msgBox("Error downloading " + currentActivity);
}
var o = Utilities.jsonParse(result.getContentText());
// set title
var titleCell = doc.getRange("a1");
titleCell.setValue("date");
var cell = doc.getRange('a2');
// fill the spreadsheet with the data
var index = 0;
for (var i in o) {
// set title for this column
var title = i.substring(i.lastIndexOf('-') + 1);
titleCell.offset(0, 1 + activity * 1.0).setValue(title);
var row = o[i];
for (var j in row) {
var val = row[j];
cell.offset(index, 0).setValue(val["dateTime"]);
// set the date index
cell.offset(index, 1 + activity * 1.0).setValue(val["value"]);
// set the value index index
index++;
}
}
}
}
function isConfigured() {
return getConsumerKey() != "" && getConsumerSecret() != "";
}
function setConsumerKey(key) {
ScriptProperties.setProperty(CONSUMER_KEY_PROPERTY_NAME, key);
}
function getConsumerKey() {
var key = ScriptProperties.getProperty(CONSUMER_KEY_PROPERTY_NAME);
if (key == null) {
key = "";
}
return key;
}
function setLoggables(loggable) {
ScriptProperties.setProperty("loggables", loggable);
}
function getLoggables() {
var loggable = ScriptProperties.getProperty("loggables");
if (loggable == null) {
loggable = LOGGABLES;
} else {
loggable = loggable.split(',');
}
return loggable;
}
function setFirstDate(firstDate) {
ScriptProperties.setProperty("firstDate", firstDate);
}
function getFirstDate() {
var firstDate = ScriptProperties.getProperty("firstDate");
if (firstDate == null) {
firstDate = "2012-01-01";
}
return firstDate;
}
function formatToday() {
var todayDate = new Date;
return todayDate.getFullYear()
+ '-'
+ ("00" + (todayDate.getMonth() + 1)).slice(-2)
+ '-'
+ ("00" + todayDate.getDate()).slice(-2);
}
function setConsumerSecret(secret) {
ScriptProperties.setProperty(CONSUMER_SECRET_PROPERTY_NAME, secret);
}
function getConsumerSecret() {
var secret = ScriptProperties.getProperty(CONSUMER_SECRET_PROPERTY_NAME);
if (secret == null) {
secret = "";
}
return secret;
}
// function saveSetup saves the setup params from the UI
function saveSetup(e) {
setConsumerKey(e.parameter.consumerKey);
setConsumerSecret(e.parameter.consumerSecret);
setLoggables(e.parameter.loggables);
setFirstDate(e.parameter.firstDate);
var app = UiApp.getActiveApplication();
app.close();
return app;
}
// function onOpen is called when the spreadsheet is opened; adds the Fitbit menu
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [{
name: "Sync",
functionName: "sync"
}, {
name: "Setup",
functionName: "setup"
}, {
name: "Authorize",
functionName: "authorize"
}];
ss.addMenu("Fitbit", menuEntries);
}
// function onInstall is called when the script is installed (obsolete?)
function onInstall() {
onOpen();
}
Problem solved with updated code at https://github.com/loghound/Fitbit-for-Google-App-Script

How do I create an anonymous JavaScript function/callback with Dart's JS interop?

I am using Dart and its JS interop. I need to convert the following JavaScript code to Dart:
ID3.loadTags("filename.mp3", function() {
var tags = ID3.getAllTags("filename.mp3");
if (tags.artist)
artist.textContent = tags.artist;
if (tags.title)
track.textContent = tags.title;
}, {
dataReader: FileAPIReader(file)
});
Note the anonymous callback as the second parameter to loadTags. How do I create that with Dart and the dart:js library?
The closest I got was creating a named function with:
js.context['loadTagsCallback'] = () {
var tags = ID3.callMethod('getAllTags', ["filename.mp3"]);
var artistTag = tags['artist'];
var titleTag = tags['title'];
if (artistTag != null) {
artist.text = artistTag;
}
if (titleTag != null) {
track.text = titleTag;
}
};
And then using this Dart code:
ID3.callMethod('loadTags', [
"filename.mp3",
js.context['loadTagsCallback'],
new js.JsObject.jsify({'dataReader': id3FileReader})
]);
However, I don't want to create the named function. Any ideas or tips?
Dart closures are automatically converted to JS closures when sent across the border. You can just do this:
ID3.callMethod('loadTags', ["filename.mp3", () {
var tags = ID3.callMethod('getAllTags', ["filename.mp3"]);
var artistTag = tags['artist'];
var titleTag = tags['title'];
if (artistTag != null) {
artist.text = artistTag;
}
if (titleTag != null) {
track.text = titleTag;
}
},
new js.JsObject.jsify({'dataReader': id3FileReader})
]);

An observer for page loads in a custom xul:browser

In my firefox extension I'm creating a xul:browser element. I want to have an observer that intercepts any url changes within the embedded browser and opens the url in a new browser tab (in the main browser). I'd also like new windows spawned by the xul:browser window to open in a tab instead of a new browser window.
I've created an observer which works, but I don't yet know how to apply that observer only to the xul:browser element.
function myFunction(){
var container = jQuery("#container")[0];
var new_browser_element = document.createElement('browser');
container.appendChild(new_browser_element);
var observerService = Components.classes["#mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
observerService.addObserver(myObserver, "http-on-modify-request", false);
}
var myObserver = {
observe: function(aSubject, aTopic, aData){
if (aTopic != 'http-on-modify-request'){
aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
// alert(aSubject.URI.spec);
// Now open url in new tab
}
},
QueryInterface: function(iid){
if (!iid.equals(Components.interfaces.nsISupports) &&
!iid.equals(Components.interfaces.nsIObserver))
throw Components.results.NS_ERROR_NO_INTERFACE;
return this;
}
};
You could try:
var myObserver = {
observe: function(aSubject, aTopic, aData){
if (aTopic == 'http-on-modify-request')
{
aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
var url = aSubject.URI.spec;
var postData ;
if (aSubject.requestMethod.toLowerCase() == "post")
{
var postText = this.readPostTextFromRequest(request);
if (postText)
{
var dataString = parseQuery(postText);
postData = postDataFromString(dataString);
}
}
var oHttp = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
var interfaceRequestor = oHttp.notificationCallbacks.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow);
//check if it is one of your mini browser windows
if (jQuery(DOMWindow).hasClass('mini_browser'))
{
openInTab(url, postData);
var request = aSubject.QueryInterface(Components.interfaces.nsIRequest);
request.cancel(Components.results.NS_BINDING_ABORTED);
}
}
},
QueryInterface: function(iid){
if (!iid.equals(Components.interfaces.nsISupports) &&
!iid.equals(Components.interfaces.nsIObserver))
throw Components.results.NS_ERROR_NO_INTERFACE;
return this;
},
readPostTextFromRequest : function(request) {
var is = request.QueryInterface(Components.interfaces.nsIUploadChannel).uploadStream;
if (is)
{
var ss = is.QueryInterface(Components.interfaces.nsISeekableStream);
var prevOffset;
if (ss)
{
prevOffset = ss.tell();
ss.seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, 0);
}
// Read data from the stream..
var charset = "UTF-8";
var text = this.readFromStream(is, charset, true);
// Seek locks the file so, seek to the beginning only if necko hasn't read it yet,
// since necko doesn't seek to 0 before reading (at lest not till 459384 is fixed).
if (ss && prevOffset == 0)
ss.seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, 0);
return text;
}
else {
dump("Failed to Query Interface for upload stream.\n");
}
}
return null;
},
readFromStream : function(stream, charset, noClose)
{
var sis = Components.classes["#mozilla.org/binaryinputstream;1"]
.getService(Components.interfaces.nsIBinaryInputStream);
sis.setInputStream(stream);
var segments = [];
for (var count = stream.available(); count; count = stream.available())
segments.push(sis.readBytes(count));
if (!noClose)
sis.close();
var text = segments.join("");
return text;
}
};
function openInTab(url, postData)
{
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var recentWindow = wm.getMostRecentWindow("navigator:browser");
if (recentWindow)
{
// Use an existing browser window, open tab and "select" it
recentWindow.gBrowser.selectedTab = recentWindow.gBrowser.addTab(url, null, null, postData);
}
}
function parseQuery() {
var qry = this;
var rex = /[?&]?([^=]+)(?:=([^&#]*))?/g;
var qmatch, key;
var paramValues = {};
// parse querystring storing key/values in the ParamValues associative array
while (qmatch = rex.exec(qry)) {
key = decodeURIComponent(qmatch[1]);// get decoded key
val = decodeURIComponent(qmatch[2]);// get decoded value
paramValues[key] = val;
}
return paramValues;
}
function postDataFromString(dataString)
{
// POST method requests must wrap the encoded text in a MIME
// stream
var stringStream = Components.classes["#mozilla.org/io/string-input-stream;1"]
.createInstance(Components.interfaces.nsIStringInputStream);
if ("data" in stringStream) // Gecko 1.9 or newer
stringStream.data = dataString;
else // 1.8 or older
stringStream.setData(dataString, dataString.length);
var postData = Components.classes["#mozilla.org/network/mime-input-stream;1"].
createInstance(Components.interfaces.nsIMIMEInputStream);
postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
postData.addContentLength = true;
postData.setData(stringStream);
return postData;
}
I'll update this to fill in the blanks in a bit.
edit: see http://forums.mozillazine.org/viewtopic.php?p=2772951#p2772951 for how to get the source window of a request.
Request cancellation code from http://zenit.senecac.on.ca/wiki/index.php/Support_For_OpenID.
see http://mxr.mozilla.org/mozilla-central/source/netwerk/base/public/nsIRequest.idl for details on nsIRequest.
See http://forums.mozillazine.org/viewtopic.php?p=2404533#p2404533 and https://developer.mozilla.org/en/XUL/Method/addTab for the definition of addTab.
parseQuery comes from http://blog.strictly-software.com/2008/10/using-javascript-to-parse-querystring.html.
See https://developer.mozilla.org/en/Code_snippets/Post_data_to_window#Preprocessing_POST_data for how to process post data in a form suitable for addTab.
ReadPostFromText and ReadTextFromStream both come from firebug (though slightly modified)

Resources