jquery hide/show is not working as expected in node js - javascript

I am new to node js, I am building one application for learning purpose.
I stuck in a thing, where I have to do show/hide of success and error message.
Here I have used jquery plugin in node js.
Below is the code :
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;
global.jQuery = require('jquery')(window);
global.$ = global.jQuery;
registration code :
doRegistration : (req , res) => {
let email = req.body.email;
let password = req.body.password;
let name = req.body.name;
let confirm_password = req.body.confirm_password;
let encryptedString = cryptr.encrypt(req.body.password);
if(email== '' || password == '' || name =='' || confirm_password =='')
{
message = "Fields are empty";
let list2 = [];
list2.name = '';
list2.email = '';
if(name!='')
{
list2.name =name;
}
if(email!='')
{
list2.email = email;
}
req.flash('error', message);
setTimeout(function(){ $("#err").hide(); },3000); //not working
res.locals.message = req.flash();
res.render('registration.ejs' ,{
code : '204',
title: "Registration",
details :list2,
});
}
}
setTimeout(function(){ $("#err").hide(); },3000); this code has been added to hide the error message .Error message is not getting hide.
Is there anything wrong in my code.
Please suggest.
Thank you

You have a bunch of code (in your first code block) which sets up a DOM and jQuery. You don't seem to ever populate the document with any data, but that's not your biggest problem.
In your registration code, you collect some data, inject it into registration.ejs and send the result to the client.
Three seconds later (by which time the HTTP request is finished, and the browser has whatever your sent), you call a jQuery function. This function operates on whatever global.document is.
global.document doesn't appear to have anything to do with registration.ejs and, even if it did, would change what was currently on the server without touching whatever is on the browser.
You can't write server-side JS that travels back in time and changes what the server sent to the browser three seconds earlier.
You could instead include a <script> element in the template file and run your jQuery client-side.
You can't write server-side code which initiates a connection to the browser (HTTP works with the browser initiating a communication with a request and the server providing a response) telling it to display a different document instead.
You could use WebSockets (or less elegant approaches like Comet or polling) so that when the page loads in the browser it initiates a connection to the server and then signal the browser to run some client-side code which hides the element. You still need to do the hiding with client-side code, this just allows you to determine when that happens on the server. There's no need for anything that complex if you just want to wait a short time.

Related

Send data from Server script to Client script (and not the other way around)

I am working on a widget, and I use data/input variables to communicate between the Client script to Server script.
for ex., in the Client Script I use:
c.data.action= "removeEvent";
c.server.update().then(function(){ c.data.action = undefined;});
and I am waiting that action in the Server Script with:
if(input.action == "removeEvent"){
//some code here...
}
My problem is that once I completed that action (in the Server Script) I need to go back to my Client Script to updated the data that is showed to the user and trigger other functions. So, how can I know from the Client Script that the code in the Server Script has ended?
I try to use the data variable again like:
// In Server Script
data.finished = true;
//In client Script
if(data.finished ) {
//do something
}
But, the Client Script doesn't update.
Is there a way to do it with a watcher or subscribe on a variable so when it changes I know that the Server Script has finished?
Thanks all for your help!
To an extent this will depend on your client - Whether the client is service portal, platform UI, seismic+UIB page etc.
In general you have 2 options in this case
Record watcher: https://developer.servicenow.com/dev.do#!/learn/learning-plans/quebec/servicenow_application_developer/app_store_learnv2_serviceportal_quebec_recordwatch
OR
Flow designer: Create a flow which will watch the server script or side-effect of server script like change to a record in database and based on that inject an action which will trigger refresh on the client UI.
In either case the client will need a callable hook that can be called by the server backend.
I ended up using GlideAjax and Scripts Includes that allows you to create functions that have return values for asynchronous or synchronous calls.
Exemple:
First, create the Ajax Call and their return function:
var ga = new GlideAjax("ucd_GetLocationData");
ga.addParam("sysparm_name", "getCampus");
ga.addParam("sysparm_buildingid", g_form.getValue("u_building"));
ga.getXML(updateCampus);
function updateCampus(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
var clearvalue; // Stays Undefined
if (answer) {
var returneddata = JSON.stringify(answer);
g_form.setValue("campus", returneddata.sys_id, returneddata.name);
} else {
g_form.setValue("campus", clearvalue);
}
}
Finally, create a Server Script (Script Include):
var ucd_GetLocationData = Class.create();
ucd_GetLocationData.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getCampus: function() {
var buildingid = this.getParameter("sysparm_buildingid");
var loc = new GlideRecord("cmn_location");
if (loc.get(buildingid)) {
var campus = new GlideRecord("cmn_location");
if (campus.get(loc.parent)) {
var json = new JSON();
var results = {
sys_id: campus.getValue("sys_id"),
name: campus.getValue("name")
};
return json.parse(results);
}
} else {
return null;
}
}
});
Check the tutorial from here:
https://sn.jace.pro/getting-started/GlideAjax/

Outlook AddIn GetAsync successful but returns nothing

I've got an Outlook Add In that was developed using the Office Javascript API.
It looks at the new email being composed & does things based on who it's going to: https://learn.microsoft.com/en-us/office/dev/add-ins/reference/objectmodel/requirement-set-1.3/office.context.mailbox.item
The code correctly returns the TO email when you 'select' the email from the suggested email list... screenshots shown # bottom of this thread
To debug the Javascript, I use C:\Windows\SysWOW64\F12\IEChooser.exe
It was working fine until last week. Is it possible a Windows update broke functionality?
I'm the only person with access to the code. It hadn't been modified for months.
When debugger is running, getAsync correctly returns the 'TO' value. I needed to write the response to a global variable to prove the values were 'undefined' while not in debug.
var resultObjects;
var resultObjects2;
var strMessages = '';
var strTo = '';
var mailbox;
var mailitem;
(function () {
"use strict";
// The Office initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
mailbox = Office.context.mailbox;
mailitem = mailbox.item;
mailitem.to.getAsync(function (result) {
if (result.status === 'failed') {
strMessages = 'FAILED';
} else {
strMessages = 'SUCCESS';
strTo = result.value[0];
resultObjects = result;
resultObjects2 = result.value;
}
});
loadApp();
});
};
})();
Here are the values of the variables, when the app is loaded & debugger is not running
EDIT
If you 'select' the TO email so that it is bolded... the code works correctly. If you leave the typed-in-text field without selecting the suggested email, it does not work. The same behavior is true for both the Outlook Web Application (# https://outlook.office.com) and the desktop outlook application.
Does not work
Does Work
The Office.context.mailbox.item.to.getAsync API will only return resolved recipients. If the TO email address is not resolved (as in the first screenshot titled "Does not Work"), then API will not return the email address until it is resolved (in both desktop and OWA).
You can use the RecipientsChanged Event, to get newly resolved recipients after you have queried for to.getAsync. This event would fire when a recipient is newly resolved.

Make NodeJS/JSDom wait for full rendering before scraping

I'm trying to scrape data from a website that I need to log into. Unfortunately, I'm getting different results using JSDom/NodeJS than I would if I were to use a web browser, such as FF. In particular, I'm not getting the log in form with the username, password and submit button.
I understand much of Javascript, at least, is asynchronous. However, I thought the "done" function of JSDom waits synchronously for the full rendering of the page. I guess what I'd like to do is simulate an HTTPS get and wait for the full document.ready to be done.
var jsdom = require("jsdom");
var jsdom_global = require("jsdom-global");
var fs = require("fs");
var jquery = fs.readFileSync("./jquery-3.1.1.min.js", "utf-8");
jsdom.env({
url: "https://wemc.smarthub.coop/Login.html#login:",
src: [jquery],
done: function (err, window) {
var $ = window.$;
if($("button#LoginSubmitButton").length) {
console.log('Click button found');
} else {
console.log('Click button not found');
}
// The following text boxes are not coming back:
// $("input#LoginUsernameTextBox")
// $("input#LoginPasswordTextBox")
// If I enable the line below, I see a lot less than I would if I
// do a view source in any reasonable browser.
//console.log($("body").html());
}
});
Usually, this will happen because JSDOM doesn't execute the JS when it hits the page. In that case, the only elements returned will be the server rendered HTML.
You could try a headless browser module such as PhantomJS etc and see how that goes for you. There's a section about the distinction between the two at the bottom of the JSDOM github page.

strophe.js and openfire who terminates connection on page reload?

I am using symfony2 to build some app. In that app I have chat app. I am using attached session in chat.
1) On login I fire up event listener to catch user/pass from login, connect to openfire server and get sid and rid.
2) After that i am storing that data in session so I can use them later on every page where I have chat.
Problem occurs when page is reloaded/refreshed.
My guess this is because ajax request to url:7070/httpd-bind is canceled strophe sends terminate to openfire server. Bu I can not find anywhere terminate stanza.
I am have patched strophe.js to use sync on page unload but again that is not working.
Chat.connection.flush();
Chat.connection.sync = true; // Switch to using synchronous requests since this is typically called onUnload.
Chat.connection.disconnect();
Please suggest solution for this, I am on 10 hour coding and I have no idea how to solve this.
I can sotre user/pass in session but that is just stupid. Why attached session exists if I have to do that.
UPDATE
After trying to figure about this rid plus+1 etc I noticed that rid is changing on presence, on message on message sent on roster on roster change so I made a XMLHttpRequest on each to remember new rid in session. For some reason localstorage is sometimes working sometimes not.
Now i have rid up to date all the time.
I think I got this. Problem was in rid and presence.
1) First you have to figure out from your logs if your rid is increasing or decreasing.
My was decreasing by one. So I substract -1 from my Chat.connection.rid
2) In my openfire logs I figured out that I was sending unavailable status on page refresh
so I changed my window.unload function to send presence to online. N
Now I am refreshing page million times and i never got disconnected.
Now I just have to figure out how to remember connection.rid to localStorage for non HTML browsers.
To start openfire in debug mode you just add ./openfire.sh -debug. Then you will be able to se everything in debug.log
This did trick for me. If this is doing trick for you please +1 and accept answer.
Do not forget to terminate session on logout :)
UPDATE
This is my on window.onunload function
window.onunload = function(ev){
var initialPresence = $pres().c('show').t("cao").up().c('status').t("sad");
Chat.connection.send(initialPresence);
store.set('session_rid', parseInt(Chat.connection.rid)-1);
//save rooster contacts state
var contacts = document.getElementById('records').getElementsByTagName('li');
var id_value;
var class_value;
var status;
var el;
for(i= 0; i < contacts.length; i++){
el = contacts[i].getElementsByClassName("mood")[0];
status = el.textContent || el.innerText;
Array.prototype.slice.call(contacts[i].attributes).forEach(function(item) {
if(item.name == "id"){
id_value = item.value;
}
if(item.name == "class"){
class_value = item.value;
}
store.set('user'+i, { id: id_value, class_name: class_value, status : status });
});
}
Chat.disconnect();
}
This is my on window.onload function
window.onload = function(){
if(store.get("session_rid")){
var obj;
var id;
var class_name;
var status;
store.forEach(function(val, key) {
if(val !== "session_rid"){
setTimeout(function(){
obj = eval(key);
id = obj.id;
class_name = obj.class_name;
status = obj.status;
if(document.getElementById(id)){
document.getElementById(id).className = class_name;
document.getElementById(id).getElementsByClassName("mood")[0].innerHTML = "<span>"+status+"</span>";
}
}, 1000);
}
})
}
}
This is working for me. I used store.js to store data so it can work on IE.
I used attached sessions.
//json is from ajax call on some php script that has started attached session on user login
var obj = JSON.parse(json);
connection = new Strophe.Connection(BOSH_SERVICE);
connection.attach(obj.fulljid,
obj.sid,
(store.get("session_rid") ? store.get("session_rid"):obj.rid),
justDoIt);
full_jid = obj.fulljid;

Get notified when JS breaks?

I have configured PHP to send me mails whenever there is an error. I would like to do the same with Javascript.
Also given the fact that this will be client side it is open to abuse.
What are good ways to get notified by mail when JS breaks in a web application?
Update:
Just to give some perspective, i usually load several js files including libraries (most of the time jQuery).
You can listen to the global onError event.
Note that you need to make sure it doesn't loop infinitely when it raises an error.
<script type="text/javascript">
var handlingError = false;
window.onerror = function() {
if(handlingError) return;
handlingError = true;
// process error
handlingError = false;
};
</script>
The code below relies on the global onError event, it does not require any external library and will work in any browser.
You should load it before any other script and make sure you have a server-side jserrorlogger.php script that picks up the error.
The code includes a very simple self-limiting mechanism: it will stop sending errors to the server after the 10th error. This comes in handy if your code gets stuck in a loop generating zillions of errors.
To avoid abuse you should include a similar self-limiting mechanism in your PHP code, for example by:
saving and updating a session variable with the error count and stop sending emails after X errors per session (while still writing them all down in your logs)
saving and updating a global variable with the errors-per-minute and stop sending emails when the threshold is exceeded
allowing only requests coming from authenticated users (applies only if your
application requires authentication)
you name it :)
Note that to better trace javascript errors you should wrap your relevant code in try/catch blocks and possibly use the printstacktrace function found here:
https://github.com/eriwen/javascript-stacktrace
<script type="text/javascript">
var globalOnError = (function() {
var logErrorCount = 0;
return function(err, url, line) {
logErrorCount++;
if (logErrorCount < 10) {
var msg = "";
if (typeof(err) === "object") {
if (err.message) {
// Extract data from webkit ErrorEvent object
url = err.filename;
line = err.lineno;
err = err.message;
} else {
// Handle strange cases where err is an object but not an ErrorEvent
buf = "";
for (var name in err) {
if (err.hasOwnProperty(name)) {
buf += name + "=" + err[name] + "&";
}
}
err = "(url encoded object): " + buf;
}
}
msg = "Unhandled exception ["+err+"] at line ["+line+"] url ["+url+"]";
var sc = document.createElement('script'); sc.type = 'text/javascript';
sc.src = 'jserrorlogger.php?msg='+encodeURIComponent(msg.substring(0, Math.min(800, msg.length)));
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sc, s);
}
return false;
}
})();
window.onerror = globalOnError;
</script>
You would wrap your entire program in a try/catch and send caught exceptions over AJAX to the server where an email could be generated. Short of that (and I wouldn't do that) the answer is "not really."
JA Auide has the basic idea. You could also go somewhat in between, ie.:
Write an AJAX "errorNotify" function that sends error details to the server so that they can be emailed to you.
Wrap certain parts of your code (the chunks you expect might someday have issues) with a try/catch which invokes errorNotify in the catch block.
If you were truly concerned about having 0 errors whatsoever, you'd then be stuff with try/catching your whole app, but I think just try/catching the key blocks will give you 80% of the value for 20% of the effort.
Just a note from a person that logs JavaScript errors.
The info that comes from window.onerror is very generic. Makes debugging hard and you have no idea what caused it.
User's plugins can also cause the issue. A very common one in certain Firebug versions was toString().
You want to make sure that you do not flood your server with calls, limit the amount of errors that can be sent page per page load.
Make sure to log page url with the error call, grab any other information you can too to make your life easier to debug.

Categories

Resources