Prevent Server side event from firing until clientside is done - xpages

I have a button that contains clientside code and serverside code. The clientside code contains an addCallback function to execute additional code dependent on the result of the first. This all works fine, but now I am trying to add serverside JS to run AFTER the clientside is completely finished.
For some reason the serverside code and refresh is running after the first RPC is called and skipping the remainder of the clientside code.
Note: My RPC returns a string "true" or "false".
message = "Starting Initiate Settlement Process...";
$(".infoMessage").text(message);
atmID = $("input.atmID").val(); //pull from hidden input
settlementCorrectYN = $( "input:checked" ).val();
todayAmt = $( ".todayAmt" ).val();
amtReceived = $( ".amtRec" ).val();
var tranType = "Settlement";
var deferred = atmRPC.closeATMSettle(tranType);
deferred.addCallback(function(result){
alert("first result=" + result);
SERVER REFRESH RUNS HERE
if (result == "false") {
message = "Initiate Settlement process failed";
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
} else if (result == "true"){
var tranType = "Settlement";
var deferredInner = atmRPC.settleATMInitiate(settlementCorrectYN, tranType, todayAmt, amtReceived, atmID);
deferredInner.addCallback(function(result){
alert("inner result=" + result)
if (result == "false") {
message = "";
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
} else if(result == "true"){
message = atmID + " has been successfully Settled."
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
}
})
}
}
)
This happens if the server refresh is a partial or full refresh. How can I force the SSJS and accompanying refresh to run ONLY at the end.

The deferred call is executed in asynchronous way, so the code keeps running and the server code is triggered. You need to change this call to a "synchronous" way. (Although this is strongly not recommended)

You can go old school - make your XPages button do no submission and execute your clientside code.
Have a hidden button with a classSelector which also has a style of display:none
in your callback
$('.classSelector).click()
Where the class selector is added to the XPages button that you want to click
<xp:button id="stevesId" styleClass="classSelector"></xp:button>

Related

console.log fires no matter what in node if statement

Okay, I'm experimenting with node.
var http = require("http");
// function myFunction()
// {
// console.log("Hello");
// }
function newServer(req, res)
{
if (req.url == "/")
{
res.end("default url");
}
else
{
res.end("other url");
console.log("Hello");
//why does this fire no matter what?
//infact if I change it to "req.url == '/f'" this console.log fires twice. WTF!
}
}
var myserver = http.createServer(newServer)
myserver.listen(7000);
The comment I left in the "else" statement basically sums up my issue. As soon as I go to localhost:7000, the console.log message fires. If I use "if(req.url == '/')" it fires immediately once I got to "http://localhost:7000/", if I use "if(req.url =='/f')" it fires twice as soon as I got to "http://localhost:7000/". Not localhost:7000/f, just regular old localhost:7000. If I do go to fire localhost:7000/f, it will fire one more time. What's the deal? It seems it first one every render, and then checks the if statement to see if it should fire again.

Chrome Plugin Manifest V3 - strange behavior of a promise function in popup.js

I'm trying to create a small plugin to make my day-to-day job easier. I have faced a very strange situation within the popup.js script. The promise function randomly refuses to get executed. I have spent some hours trying to debug or at least understand where the issue could be but without any results.
Here is the skeleton of the code:
document.addEventListener('DOMContentLoaded', function () {
// some initialization
document.getElementById("signinbutton").addEventListener("click", function(event) {
try {
// some more initialization
var user_email = '';
var advertiserId = '';
var checkibm = '';
user_email = $('#emailfield').val().trim();
advertiserId = $('#advertiseridfield').val().trim();
checkibm = $('#checkibm').is(':checked');
if (advertiserId && checkibm) {
_act = 'getTokenIdByAdvId',
_data = advertiserId
}
else if (advertiserId && !checkibm) {
_act = 'getTokenIdByAdvId',
_data = advertiserId
}
else if (user_email && validateEmail(user_email))
{
_act = 'getTokenIdByEmail',
_data = user_email
}
else
{
throw new Error("Valid input has not been provided");
}
sendMessagePromise({
act : 'getTokenIdByAdvId',
data: '16910'//encodeURIComponent(user_email)
})
.then(responseHandler)
.then(responseReplaceTokenHandler)
.then(show_ok('Done'))
.catch(failureCallback);
}
catch (error){
//doing some error catching here
});
});
The code above works perfectly. However, as soon as I fill in the real values in sendMessagePromise e.g
//_act and _data show the proper values when inspected
sendMessagePromise({
act : _act,
data: _data//encodeURIComponent(user_email)
})
the flow skips execution of sendMessagePromise and any other chained function, except the last one ".then(show_ok('Done'))", i.e the only result is the "Done" message on the screen.
I made sure the values are correct. I'm able to debug step-by-step and see the values being properly supplied. I have also put a bunch of console messages inside the chain promise functions to see where the execution gets stuck, but it seems like it doesn't even start executing sendMessagePromise.
As soon as I replace expression back to hardcoded values i.e
sendMessagePromise({
act : 'getTokenIdByAdvId',
data: '16910'//encodeURIComponent(user_email)
})
it starts working again. I'm really stuck and not sure how to debug or which steps to take further.
Please assist

How to identify a tab is reloading, I mean actual page reload

How to identify a tab is reloading, I mean actual page reload?
I see chrome.tabs.onUpdated event, but for this event status is 'loading' even in case of AJAX calls from a webpage.
How can I detect a page is getting reloaded ?
You are right, looks like not possible to recognize AJAX and page reload calls. As workaround you could listen for onunload event for tab webpage. You probably need to check if tabid and url were not changed after that.
But do you really need to know if page reloaded?
It's an old question, but here is my solution that could be in help (without AIAX).
Since the method 'chrome.tabs.get()' return a promise, you can use the 'callback function' to check the current 'tab.status'.
Setting a boolean variable 'waitingForComplete = true', you will run your code, only when the tab will return at status = 'complete'.
background.js
var waitingForComplete = false;
chrome.tabs.onUpdated.addListener((tabId. changeInfo,tab) => {
if(changeInfo.status == 'complete'){
if(waitingForComplete){
waitingForComplete = false;
// runYourCode...
}
}
};
function checkTabStatusComplete(tabId){
chrome.tabs.get(tabId. function(tab){
if(tab.status == 'complete'){
// runYourCode...
} else {
waitingForComplete = true;
}
}
};

SP.Ribbon.WebPartComponent.getWebPartAdder() returns undefined

I am using the source at http://blog.symprogress.com/2010/11/ribbon-insert-any-web-part-using-javascript/ to handle user web part button click event.
The function 'addWebPart()' calls a function 'SP.Ribbon.WebPartComponent.getWebPartAdder()' which is supposed to return adder instance but sometimes it returns undefined.
If I add a while loop to wait for the instance value to return correctly, the browser in my VM stalls for some time. When an instance is returned, the browser becomes responsive again. This only happens in some instances.
I am using SharePoint 2013 and the section of code I am referring to is:
addWebPart = function (wpCategory, wpTitle) {
var webPartAdder = SP.Ribbon.WebPartComponent.getWebPartAdder();
while (webPartAdder == undefined)
webPartAdder = SP.Ribbon.WebPartComponent.getWebPartAdder();
// ... Other stuff ...
}
How can this issue be resolved?
For anyone looking for an answer to this question, turns out you have to call 'LoadWPAdderOnDemand()' function then wait for the event '_spEventWebPartAdderReady'. Then query for 'window.WPAdder':
addWebPartDelayed = function (webPartAdder, wpCategory, wpTitle) {
var webPart = findWebPart(webPartAdder, wpCategory, wpTitle);
if (webPart) {
var zone = WPAdder._zones[0];
var wpid = WPAdder._createWebpartPlaceholderInRte();
WPAdder.addItemToPageByItemIdAndZoneId(webPart.id, zone.id, 0, wpid);
}
else
alert('ERROR: Web part not found! Please try again after sometime.');
},
addWebPart = function (wpCategory, wpTitle) {
var webPartAdder = window.WPAdder;
if (webPartAdder == undefined) {
LoadWPAdderOnDemand();
ExecuteOrDelayUntilEventNotified(
function () {
var webPartAdder = window.WPAdder;
addWebPartDelayed(webPartAdder, wpCategory, wpTitle);
},
"_spEventWebPartAdderReady");
}
else
addWebPartDelayed(webPartAdder, wpCategory, wpTitle);
};

No blocking operation in MongoJS

I have to do an operation that calculate for me something, but I can't use the result of it, because I always stay in a wait state, in fact in my terminal remains in execution my program until I enter ctrl+C.
I have a main in nodejs for my program where I need to use my result calculated in a module.
var myJSONClient = {
"nombre" : "<nombre_cliente>",
"intervalo" : [0,0]
};
var intervalo = gestionar.gestion(myJSONClient,vector_intervalo);
console.log("intervalo: "+intervalo); //return undefined
And this is the module
var gestion = function(myJSON,vector_intervalo) {
var dburl = 'localhost/mongoapp';
var collection = ['clientes'];
var db = require('mongojs').connect(dburl, collection );
var intervalo_final;
function cliente(nombre, intervalo){
this.nombre = nombre;
this.intervalo = intervalo;
}
var cliente1 = new cliente(myJSON.nombre,myJSON.intervalo);
db.clientes.save(cliente1, function(err, saveCliente){
if (err || !saveCliente) console.log("Client "+cliente1.nombre+" not saved Error: "+err);
else console.log("Client "+saveCliente.nombre+" saved");
intervalo_final = calculate(vector_intervalo);
console.log(intervalo_final); //here I can see the right content of the variable intervalo_final
});
console.log(intervalo_final); //this is not executed
return intervalo_final;
}
exports.gestion = gestion;
Welcome to the async world! :)
First of all, you aren't doing blocking operations in Node. Actually, networking in Node is fully asynchronous.
The part you state the console.log works it's because the callback function of the db.clientes.save call. That callback states your mongo save has finished.
What asynchronous networking means?
It means that your save will be processed sometime in the future. The script will not wait for the response to continue the code. The console.log right after the save call will be executed soon as it's reached.
As for the "wait state" of your script, that it never ends, you should take a look at this question. There's the answer.

Resources