How to hand an object from backend to frontend - html

I try to create a Web App. Therefor I have to pass an Object from the backend to the HTML-Script. I tried a lot of possibilites but nothing worked.
Backend
function searchMain (allSeaVal) {
var headCon = DbSheet.getRange(1, 1, 1, DbSheet.getLastColumn()).getValues();
var bodyCon = DbSheet.getRange(valRow, typesCol, 1, DbSheet.getLastColumn()).getValues();
var Con = {
headline: headCon,
values: bodyCon
};
var tmp = HtmlService.createTemplateFromFile('page_js');
tmp.Con = Con.map(function(r){ return r; });
return tmp.evaluate();
}
HTML
<script>
function searchValues() {
var allSeaVal = {};
allSeaVal.seaType = document.getElementById('valSearchTyp').value;
allSeaVal.seaVal = document.getElementById('HSearchVal').value;
google.script.run.searchMain(allSeaVal);
Logger.log(Con);
}
<script/>
I want to use the information in "Con" in the Website. The script-code is stored in the file "page_js.
I don´t know why but I can´t pass the information into the frontend.

In your html interface you have to use the success and failure handler in your google.script.run.
Code will looks like
google.script.run
.withSuccessHandler(
function(msg) {
// Respond to success conditions here.
console.log('Execution successful.');
})
.withFailureHandler(
function(msg) {
// Respond to failure conditions here.
console.log('Execution failed: ' + msg, 'error');
})
.searchMain(allSeaVal);
Do not hesitate to check the documentation : https://developers.google.com/apps-script/guides/html/communication
Stéphane

I solved my problem with your help. Thank you so much. I struggled with this many days.
My solution is the code below.
Backend
function searchMain (allSeaVal) {
var typesCol = searchTypesCol(allSeaVal.seaType);
var valRow = searchRow(allSeaVal.seaVal, typesCol);
var headCon = DbSheet.getRange(1, 1, 1, DbSheet.getLastColumn()).getValues();
var bodyCon = DbSheet.getRange(valRow, typesCol, 1, DbSheet.getLastColumn()).getValues();
var Con = {
headline: headCon,
values: bodyCon
};
return Con;
}
HTML
function searchValues() {
var allSeaVal = {};
allSeaVal.seaType = document.getElementById('valSearchTyp').value;
allSeaVal.seaVal = document.getElementById('HSearchVal').value;
google.script.run
.withSuccessHandler(
function(Con) {
console.log(Con + 'success');
})
.withFailureHandler(
function(Con) {
console.log(Con + 'failure');
})
.searchMain(allSeaVal);
}

Related

How to print external API on my server? (Take user ip address and show it on website)

I have just started using nodejs and koajs, and I would like to take the ip address from here: https://api.ipify.org?format=json and paste it on my site or set it as a header. Right now I have the following:
var koa = require('koa');
var app = koa();
var http = require('https');
var a = http.get("https://api.ipify.org?format=json",function(res) {
var data = "";
res.on("data", function (chunk) {
data += chunk;
});
res.on('end', function() {
par = JSON.parse(data);
console.log(par.ip);
});
});
app.listen(8888);
app.use(function *(){
this.response.set("userIp",par.ip);
this.body = "ipadress: "; //this doesn't see par.ip;
});
I know that I am probably doing something very wrong here but yea I am currently stuck because I have no idea how to take par.ip and assign it to this.body and set.
Would anyone be able to tell me how to achieve this or an alternative to the problem? Thanks in advance.
Assuming the response from api.ipify.org doesn't change.
var koa = require('koa');
var app = koa();
var http = require('https');
var a = http.get("https://api.ipify.org?format=json",function(res) {
var data = "";
res.on("data", function (chunk) {
data += chunk;
});
res.on('end', function() {
par = JSON.parse(data);
console.log(par.ip);
app.use(function *(){
this.response.set("userIp",par.ip);
this.body = "ipadress: "; //this doesn't see par.ip;
});
app.listen(8888);
});
});
Otherwise if the response from api.ipify.org constantly changes, you might to do the http request on every incoming request.

How to make a RESTFUL PUT call angulajrs

Im confused on how to make a RESTFUL API call with 'PUT'. I'm basically trying to save an edited profile but I'm confused on how to make the API call for it. This is what I have so far ...
var edit = angular.module('edit', ['ui.bootstrap','ngResource'])
.factory('editable', function($resource) {
return {
// get JSON helper function
getJSON : function(apicall) {
if(sessionStorage["EditUserId"] == undefined) {
// get the user id
var userid = sessionStorage["cerestiuserid"];
}
else {
var userid = sessionStorage["EditUserId"];
}
// json we get from server
var apicall = sessionStorage["cerestihome"];
// new api
return $resource(apicall + "/api/profiles/", {Userid:userid}, {'PUT': {method: 'Put'}});
}
};
});
This is the controller ...
//editable object
var object = editable.getJSON();
var edit = new object();
edit.UserName = "Hello World";
edit.$save();
Use restagular to invoke put service.
For example
admin.factory('AdminService', ['Restangular', 'AppConstants', 'AdminRestangular', 'WorkFlowRestangular', 'localStorageService',
function(Restangular, AppConstants, AdminRestangular, WorkFlowRestangular, localStorageService) {
var service = {}
service.updateAgency = function(data) {
return AdminRestangular.all(AppConstants.serviceUrls.agency).doPUT(data);
};
return service
}]);

Uncaught TypeError: Cannot read property 'pageSize' of undefined

Iam trying to apply paging to slickgrid and it shows an error in slick.pager.js as title in console and my code is
var jqxhr = $.getJSON('http://localhost:50305/Service1.svc/json/EmployeeDetails', function (data) {
dataView = new Slick.Data.DataView();
dataView.setItems(data, "EmpId");
dataView.setPagingOptions({ pageSize: 4 });
grid = new Slick.Grid("#teamGrid", dataView.rows, columns, options);
var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
alert("hi");
var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
var options = grid.getOptions();
if (options.enableAddRow != enableAddRow) {
grid.setOptions({ enableAddRow: enableAddRow });
}
});
dataView.onRowCountChanged.subscribe(function (args) {
grid.updateRowCount();
grid.render();
});
Try this:
dataView.beginUpdate();
dataView.setItems(data, "EmpId");
dataView.endUpdate();
dataView.setPagingOptions({ pageSize: 4 });
grid = new Slick.Grid("#teamGrid", dataView, columns, options);
The code doesn't really even make sense.
The line
var jqxhr = $.getJSON('http://localhost:50305/Service1.svc/json/EmployeeDetails', function (data) {
is not well formed. There should be a function body and a closing brace.
The variable jqxhr is not used anywhere. Why does this line even exist ?
`pagesize=10`
let pagesizealt
if(!this.paginator){
pagesizealt=this.pagesize.toString()
}
else{
pagesizealt=this.paginator.pageSize
}`
u have to check for paginator to initialize after initializtion provide the value of pageSize

Parallel form submit and ajax call

I have a web page that invokes long request on the server. The request generates an excel file and stream it back to the client when it is ready.
The request is invoked by creating form element using jQuery and invoking the submit method.
I would like during the request is being processed to display the user with progress of the task.
I thought to do it using jQuery ajax call to service I have on the server that returns status messages.
My problem is that when I am calling this service (using $.ajax) The callback is being called only when the request intiated by the form submit ended.
Any suggestions ?
The code:
<script>
function dummyFunction(){
var notificationContextId = "someid";
var url = $fdbUI.config.baseUrl() + "/Promis/GenerateExcel.aspx";
var $form = $('<form action="' + url + '" method="POST" target="_blank"></form>');
var $hidden = $("<input type='hidden' name='viewModel'/>");
$hidden.val(self.toJSON());
$hidden.appendTo($form);
var $contextId = new $("<input type='hidden' name='notifyContextId'/>").val(notificationContextId);
$contextId.appendTo($form);
$('body').append($form);
self.progressMessages([]);
$fdbUI.notificationHelper.getNotifications(notificationContextId, function (message) {
var messageText = '';
if (message.IsEnded) {
messageText = "Excel is ready to download";
} else if (message.IsError) {
messageText = "An error occured while preparing excel file. Please try again...";
} else {
messageText = message.NotifyData;
}
self.progressMessages.push(messageText);
});
$form.submit();
}
<script>
The code is using utility library that invokes the $.ajax. Its code is:
(function () {
if (!window.flowdbUI) {
throw ("missing reference to flowdb.ui.core.");
}
function NotificationHelper() {
var self = this;
this.intervalId = null;
this.getNotifications = function (contextId, fnCallback) {
if ($.isFunction(fnCallback) == false)
return;
self.intervalId = setInterval(function() {
self._startNotificationPolling(contextId, fnCallback);
}, 500);
};
this._startNotificationPolling = function (contextId, fnCallback) {
if (self._processing)
return;
self._processing = true;
self._notificationPolling(contextId, function (result) {
if (result.success) {
var message = result.retVal;
if (message == null)
return;
if (message.IsEnded || message.IsError) {
clearInterval(self.intervalId);
}
fnCallback(message);
} else {
clearInterval(self.intervalId);
fnCallback({NotifyData:null, IsEnded:false, IsError:true});
}
self._processing = false;
});
};
this._notificationPolling = function (contextId, fnCallback) {
$fdbUI.core.executeAjax("NotificationProvider", { id: contextId }, function(result) {
fnCallback(result);
});
};
return this;
}
window.flowdbUI.notificationHelper = new NotificationHelper();
})();
By default, ASP.NET will only allow a single concurrent request per session, to avoid race conditions. So the server is not responding to your status requests until after the long-polling request is complete.
One possible approach would be to make your form post return immediately, and when the status request shows completion, start up a new request to get the data that it knows is waiting for it on the server.
Or you could try changing the EnableSessionState settings to allow multiple concurrent requests, as described here.

Multiple messages in Chrome Extension

Let me explain the problem.
I'm developping a chrome extension and I'm stuck with a little functionnality.
I need to grab the url in the browser and retrieve something from my server to update the badgeText.
contentscript1.js
chrome.extension.sendMessage({method:"sendUrlInBrowser",urlinbrowser: location.href}, function(response) { });
contentscript2.js
chrome.extension.sendRequest({method: "getInfosUser"}, function(response) {
var url = location.href;
var id_user = response.id_user;
var default_friend_view_user = response.default_friend_view_user;
$.post("http://host/getNoteCount",
{
"url_note" : url
},
function (data)
{
var obj = $.parseJSON(data);
var note_count = obj[0].note_count;
chrome.extension.sendMessage({method:"sendNoteCount",note_count: not_count}, function(response) {
});
}
); });
background.js
var urlinbrowser = "";var note_count = "";chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {if(request.method== 'sendUrlInBrowser') urlinbrowser = request.urlinbrowser;else if(request.method== 'sendNoteCount')
{
note_count = request.note_count;
console.log(note_count);
chrome.browserAction.setBadgeText({text:""+note_count});
} });chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getInfosUser")
{
var storage = chrome.storage.local;
var items_to_retrieve = ['id_user','default_friend_view_user'];
storage.get(items_to_retrieve, function(items) {
var id_user = items.id_user;
var default_friend_view_user = items.default_friend_view_user;
if(items.id_user.replace(' ','')!='undefined')
{
sendResponse({id_user: id_user,default_friend_view_user: default_friend_view_user});
}
});
}
else
sendResponse({}); // snub them.});
The main problem actually is that I need to send the result of the cross-site request back to the background, so it has to listen to these two messages (url + result)
And I definitely can't :(
I'm quite sure I don't have to use connect() but if it does the work...
And I'm not even sure that I need 2 content-scripts.
Does anyone have any idea ? Thanks...