Fetching Data from URL in Meteor - javascript

I'm trying to pass data through a URL in meteor. When I console.log the object it is empty, however, when i refresh the page, the object is displayed correctly in console.log.
I have a button in a google maps infoWindow which has an href to the page and with the parameters i want to pass over.
Js.
var infowindow = new google.maps.InfoWindow({
content: '<div id="infowin"><p>'+name+'"s storage </p>' +
'Space: '+space+
'<p>Price: '+price+'<div>Request Storage</div>' +
});
In the template i try to access this data :
Js.
Template.storageRequest.onCreated(function () {
// Use this.subscribe inside onCreated callback
var GET = {};
var query = window.location.search.substring(1).split("&");
for (var i = 0, max = query.length; i < max; i++)
{
if (query[i] === "") // check for trailing & with no param
continue;
var param = query[i].split("=");
GET[decodeURIComponent(param[0])] = decodeURIComponent(param[1] || "");
}
Template.storageRequest.requestData = GET;
});
Any help is appreciated

Related

How do I use two variables in my function?

So I have multiple script. One script retrieves data from a Googlesheet and parses it as JSON. The other one uses this to output it to HTML.
My first:
function getStatistics() {
var sheet = SpreadsheetApp.openById("ID");
var rowsData = sheet.getRange("A:A").getValues();
var result = JSON.stringify(rowsData);
var funcNumber = 1;
return result;
}
This retrieves the data from a spreadsheet in column A.
The second script, here I want to use both 'Result' and 'Funcnumber' in my function.
function onSuccess(data, funcNumber) {
var dataJson = JSON.parse(data);
var newColumn = document.createElement("div");
newColumn.className = "column";
for(var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
Using the Json result to PARSE the HTML works. But retrieving 'funcNumber' from the function not. Then finally I call the first function with this line:
google.script.run.withSuccessHandler(onSuccess).getStatistics();
Does anybody know how to use both result and funcNumber in my second function?
function getStatistics() {
var ss = SpreadsheetApp.openById("ID");
const sheet = ss.getSheetByName('Sheet1');
let result = {data:JSON.stringify(sheet.getRange(1,1,sheet.getLastRow(),1).getValues()),funcNumber:1}
return result;
}
function onSuccess(obj) {
var dataJson = JSON.parse(obj.data).flat();
var newColumn = document.createElement("div");
newColumn.className = "column";
for (var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + obj.funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
A single column or row is still a 2d array
Following is the way to make the call in Google script to return the value for the 2nd parameter.
google.script.run
.withSuccessHandler(onSuccess)
.withUserObject(funcNumber)
.getStatistics()
WithUserObject() needs to be called after the withSuccessHandler.
See the documentation below on Google script
withUserObject(object)
Sets an object to pass as a second parameter to the success and failure handlers. This "user object" — not to be confused with the User class — lets the callback functions respond to the context in which the client contacted the server. Because user objects are not sent to the server, they are not subject to the restrictions on parameters and return values for server calls. User objects cannot, however, be objects constructed with the new operator.

ServiceNow auto-populate Script not being called

I have a table in ServiceNow that contains Store and a corresponding Tier that is associated with the Store.
I am trying to auto-populate a record producer, once Store is selected. and my script is not running.
The table is a custom table created in a scoped application which is new to me so not sure what I am doing wrong in the scripting. Any advice?
//Catalog Client Script (runs on [Store] Record Producer Change)
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
// new GlideAjax object referencing store of AJAX script include
var ga = new GlideAjax("HRProfileAjax");
// add store parameter to define which function we want to call
// method store in script include will be getFavorites
ga.addParam("sysparm_store", "getHRProfile");
ga.addParam("sysparm_tier", "getHRProfile");
// submit request to server, call ajaxResponse function with server response
ga.getXML(ajaxResponse);
function ajaxResponse(serverResponse) {
// get result element and attributes
var result = serverResponse.responseXML.getElementsByTagstore("result");
var message = result[0].getAttribute("tier");
//check for message attribute and alert user
//if(message)
//alert(message);
//build output to display on client for testing
// get favorite elements
var favorites = serverResponse.responseXML.getElementsByTagstore("favorite");
for(var i = 0; i < favorites.length; i++) {
var store = favorites[i].getAttribute("store");
g_form.setValue(store);
var tier = favorites[i].getAttribute("tier");
//output += store + " = " + tier + "\n";
g_form.setValue(store,tier);
}
//g_form.setValue('number',output);
}
//Script #2 HR PROFILE AJAX
/*
* HRProfileAjax script include Description - sample AJAX processor returning multiple value pairs
*/
var HRProfileAjax = Class.create();
HRProfileAjax.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
/*
* method available to client scripts call using:
* var gajax = new GlideAjax("HRProfileAjax");
* gajax.addParam("sysparm_store", "getFavorites");
*/
getHRProfile : function() {
// build new response xml element for result
var result = this.newItem("result");
var store = this.getParameter('store');
var hrPro = new GlideRecord('x_hiring_gri_hr_storetier');
hrPro.addQuery('store',store);
hrPro.query();
if(hrPro.next()){
result.setAttribute("message", "returning all favorites");
this._addFavorite("tier", hrPro.tier);
}
},
_addFavorite : function(store, value) {
var favs = this.newItem("favorite");
favs.setAttribute("store", store);
},
type : "HRProfileAjax"
});

how to get js var data from GDownloadUrl callback?

Now, I have tried to get some data from crawling website.
The target website provides current status of bicycle stations using google map.
GDownloadUrl("/mapAction.do?process=statusMapView", function(data, responseCode) {
var jsonData = eval("(" + data + ")");
//alert(jsonData.centerLat);
var length = jsonData.markers.length;
//if (length > 100) length = 100;
for (var i = 0; i < length; i++) {
var point = new GLatLng(parseFloat(jsonData.markers[i].lat), parseFloat(jsonData.markers[i].lng));
var name = jsonData.markers[i].name;
var cntRackTotal = jsonData.markers[i].cntRackTotal;
var cntRentable = jsonData.markers[i].cntRentable;
var cntLockOff = jsonData.markers[i].cntLockOff;
var cntPrtRack = jsonData.markers[i].cntPrtRack;
var percent = jsonData.markers[i].percent;
var imgFile = jsonData.markers[i].imgFile;
var number = jsonData.markers[i].kiosk_no;
//map.addOverlay(createMarker(number, point, name, cntRackTotal, cntRentable, cntLockOff, cntPrtRack, percent, imgFile ));
}
});
This JS source code is used on target website. In GDownloadUrl callback function, the parameter "data" contains current status of bicycle stations. And I want to get data.
Now, I tried using python selenium and execute_script().
jsSourcecode = ("var strData;"+
"strData = GDownloadUrl('/mapAction.do?process=statusMapView',"+
" function(data, responseCode) {return data;}); return strData;")
data = driver.execute_script(jsSourcecode)
this source code is that I used to get data. I expected data on callback would be stored on var strData and the return value of execute_script() would be the data. but the return value is just "True".
I have little knowledge about js.. How can I get the data? Please help
The function you are calling is asynchronous and requires a callback function as argument.
Use execute_async_script and provide the callback present in the last argument:
data, status = driver.execute_async_script("""
var callback = arguments[0];
window.GDownloadUrl('/mapAction.do?process=statusMapView', function(data, status){
callback([data, status]);
});
""")

Passing Variable from JSON data

I am building a mobile app using Titanium for ios and I am having a tough time getting my arms wrapped around passing variables. I am using a combination of local database and remote database to deliver my data. In this case I want to pass the data on the tableViewRow selected. The label that displays the data I call "categorydescription". In my table.addEventListener, I want to pass that data as the title for the new window and I will pass that same data to my php file on the remote server. Here is the code I am trying to use:
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for (i = 0; i < json.cms_client.length; i++) {
client = json.cms_client[i];
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true
});
var categorydescription = Ti.UI.createLabel({
text:client.catdesc,
font:{fontSize:'16dp', fontWeight:'bold'},
height:'auto',
left:'10dp',
color:'#000'
});
row.add(categorydescription);
tableData.push(row);
}
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: ??});
var catdesc = ??;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});
table.setData(tableData);
Would someone be so kind to tell me what I need to put in place of the ?? in the 'title' and 'var catdesc' above?
Just add the category description and title to the row object itself:
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true,
categoryDescription : client.catdesc, //Add this
clientTitle : client.title // Add this
});
Now get them in the listener:
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: e.row.title});
var catdesc = e.row.categoryDescription;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});

Getting URL data with JavaScript (split it like php $_GET)

I found this script at Stack Overflow:
window.params = function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for(var i in param_array){
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
}();
This splits a URL into data, like PHP does with $_GET.
I have another function, which uses it and it refreshes the iframe. I want to get the data from the URL and add another with it if some of these data exist. Firebug shows me, that search is not defined, but why?
function RefreshIFrames(MyParameter) {
var cat = window.params.cat;
var category = window.params.category;
var search = window.params.search;
if (search.length>0 && category.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search="+search+"&category="+category+"&rendez="+MyParameter;
}
if (cat.length>0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat="+cat+"&rendez="+MyParameter;
}
if (cat.length==0 && category.length==0 && search.length==0){
window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez="+MyParameter;
}
alert(window.location);
}
If you want to add rendez OR change the existing rendez, do this - I am assuming the URL is actually beginning with http://siriusradio.hu/kiskunfelegyhaza/video/index.php so no need to create it. Let me know if you need a different URL than the one you come in with
The parameter snippet did not work proper (for in should not be used on a normal array)
Here is tested code
DEMO
DEMO WITH DROPDOWN
function getParams(passedloc){
var params = {}, loc = passedloc || document.URL;
loc = loc.split('?')[1];
if (loc) {
var param_array = loc.split('&');
for(var x,i=0,n=param_array.length;i<n; i++) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
}
return params;
};
function RefreshIFrames(MyParameter,passedloc) { // if second parm is specified it will take that
var loc = passedloc || document.URL; //
window.param = getParams(loc);
loc = loc.split("?")[0]+"?"; // will work with our without the ? in the URL
for (var parm in window.param) {
if (parm != "rendez") loc += parm +"="+ window.param[parm]+"&";
}
// here we have a URL without rendez but with all other parameters if there
// the URL will have a trailing ? or & depending on existence of parameters
loc += "rendez="+MyParameter;
window.console && console.log(loc)
// the next statement will change the URL
// change window.location to window.frames[0].location to change an iFrame
window.location = loc;
}
// the second parameter is only if you want to change the URL of the page you are in
RefreshIFrames("rendez1","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat=cat1&search=search1");
RefreshIFrames("rendez2","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search=search2");
RefreshIFrames("rendez3","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez=xxx&search=search2");
RefreshIFrames("rendez4","http://siriusradio.hu/kiskunfelegyhaza/video/index.php");
// here is how I expect you want to call it
RefreshIFrames("rendez5"​); // will add or change rendez=... in the url of the current page

Categories

Resources