XSJS getting result from stored procedure in a variable - javascript

I have a situation where I pass a session user as a parameter to stored procedure and get a receiver value which I want to get in a variable so I can pass that to other function in xsjs file to send email.
I am getting sender from session user and doing concat to get sender email.
I am calling ReadAuditUser stored procedure will see if the appuser(session user) is valid or not
if ReadAuditUser stored procedure finds appuser as a valid user then stored procedure will return a single record which will return receiver,
if ReadAuditUser stored procedure finds appuser as a invalid user then the stored procedure will return 'null'.
I want to capture that receiver from getReceivername(), like I have capture appuser from getUsername()function.
Please let me know where I am going wrong.
function getUsername() {
var username = $.session.getUsername();
return username;
}
var appuser = getUsername();
var str2 = "#abc.com";
var sender_email = appuser.concat(str2);
function getReceivername() {
var xreceiver = "";
var conn = $.db.getConnection();
var query = 'call \"AA\".\"PROCEDURE::ReadAuditUser\"(?)';
var pstmt = conn.prepareCall(query);
pstmt.setString(1, appuser);
pstmt.execute();
var rs = pstmt.getResultSet();
if (rs.next()) {
if (rs.getString(1) === 'null') {
xreceiver = rs.getString(1);
} else {
xreceiver = rs.getString(1);
}
}
}
rs.close();
pstmt.close();
conn.close();
var receiver = getReceivername();
var str1 = "#abc.com";
var receiver_email = receiver.concat(str1);

function getUsername() {
var username = $.session.getUsername();
return username;
}
var appuser = getUsername();
var str2 = "#abc.com";
var sender_email = appuser.concat(str2);
function getReceivername() {
var xreceiver = "";
var conn = $.db.getConnection();
var query = 'call \"AA\".\"PROCEDURE::ReadAuditUser\"(?)';
var pstmt = conn.prepareCall(query);
pstmt.setString(1, appuser);
pstmt.execute();
var rs = pstmt.getResultSet();
if (rs.next()) {
if (rs.getString(1) === 'null') {
xreceiver = rs.getString(1);
} else {
xreceiver = rs.getString(1);
}
}
return xreceiver; /* have to add this code line and it works*/
}
rs.close();
pstmt.close();
conn.close();
var receiver = getReceivername();
var str1 = "#abc.com";
var receiver_email = receiver.concat(str1);

Related

restrict incident creation from record producer in servicenow

I have created a onsubmit client script: but it is not working!
When creating an incident from record producer,if Caller,Short Description and urgency matches with already existing record,Don’t Create a new record.
function onSubmit() {
var urgency = g_form.getValue('urgency');
var desc = g_form.getValue('comments');
var caller = g_user.userID;
var ga = new GlideAjax('CheckDetails');
ga.addParam('sysparm_name', 'getIncidentDetails');
ga.addParam('sysparm_urgency', urgency);
ga.addParam('sysparm_desc', desc);
ga.addParam('sysparm_caller', caller);
ga.getXML(EmployeeDetailsLookup);
}
}
function EmployeeDetailsLookup(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer) {
confirm(answer + " with same details is already present");
g_form.clearValue("urgency");
g_form.clearValue("comments");
return false;
}
}
I have used client callable scriptinclude
var CheckDetails = Class.create();
CheckDetails.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getIncidentDetails: function() {
var urgency = this.getParameter('sysparm_urgency');
var desc = this.getParameter('sysparm_desc');
var caller = this.getParameter('sysparm_caller');
var inc = new GlideRecord('incident');
inc.addEncodedQuery("urgency="+urgency + "^short_description=" + desc+"^caller_id=" + caller);
inc.setLimit(1);
inc.query();
if (inc.next()) {
return inc.number;
}
}
});

How to persist data in an array even when the page reloads, using javascript?

I have created a register and a login form using html and javascript. Where I am storing the user data in an array and then in local storage. For this I have initially declared an empty array called var users=[];
Thus, when the page reloads the previously stored data is lost as array becomes empty again and data in the local storage is overwritten. Please help, on how to avoid the array become empty after reloading the page.
Following is my controller.js-
//Declaring an empty array
var users = [];
//Setting id for each users
var idInput = makeCounter();
//Fetching data from textboxes in register.html
var firstnameInput = document.getElementById("firstname");
var lastnameInput = document.getElementById("lastname");
var emailInput = document.getElementById("email");
var usernameInput = document.getElementById("username");
var passwordInput = document.getElementById("password");
var dobInput = document.getElementById("dob");
var messageBox = document.getElementById("editeddata");
//Declaring custom constructor function
function userdetails(id, firstname, lastname, email, dob, username, password){
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.dob = dob;
this.username = username;
this.password = password;
this.FullName = this.firstname +' ' + this.lastname;
}
//counter funtion, to fetch user id
function makeCounter() {
var arraylength=users.length;
return function(){
return arraylength+1;
}
}
//insert data while registration
function registerUser()
{
//Email validation
var emailinput = document.forms["myform"]["email"].value;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!(emailinput).match(emailReg) || emailinput=="")
{
alert("Not a valid e-mail address");
return false;
}
//check, if fields are empty
if(firstnameInput.value=="" || lastnameInput.value=="" || passwordInput.value=="" || dobInput.value=="")
{
alert("Fields cannot be empty");
return false;
}
//check, if a user already exist
var usernameinput = document.forms["myform"]["username"].value;
var passwordinput = document.forms["myform"]["password"].value;
var ulen= users.length;
for(i=0; i < ulen; i++)
{
if ( usernameinput == users[i].username && passwordinput == users[i].password)
{
alert("User already exists");
return false;
}
}
var user=new userdetails(idInput(),firstnameInput.value, lastnameInput.value, emailInput.value, dobInput.value, usernameInput.value, passwordInput.value);
users.push(user);
alert("Registered successfully");
localStorage.setItem("key_users", JSON.stringify(users));
}
You can use local storage value at the time of initialisation.
if (typeof(Storage) !== "undefined") {
if (localStorage.key_users) {
users = localStorage.key_users;
} else {
users = [];
}
}
you can use something like this to check if the key is already in localStorage or not.
<html>
<head>
<link href="style.css" rel="stylesheet">
</head>
<body onload="test()">
<script>
function test(){
var value = (localStorage.getItem("key1"))
console.log(value)
if(value == null){
localStorage.setItem("key1","value1")
alert("Hellow")
}else{
var value=localStorage.getItem("key1");
alert(value)
}
}
</script>
</body>
</html>

How to obtain objectId from a parse user?

When I print user, I get : {"objectId":"insertSomeValue"} as output. But I cannot obtain the value of that objectId and store it in a string variable. How do I obtain it?
I tried user.get("objectId") and user["objectId"] but they just return "No message provided" when fed to console.log. Do I have to fetch user before I can get its objectId?
var query = new Parse.Query("HelperRating");
var newProfiles = {};
var eachPromise = Parse.Promise.as();
eachPromise = eachPromise.then(function() {
return query.each(
function (helperRating) {
var user = helperRating.get("helper");
var userId = user.objectId; // How do I get this?
console.log(user);
console.log(user.get("objectId")); // I tried these but it prints "No message provided" instead
//console.log(user["objectId"]);
var newRating = helperRating.get("rating");
// Calculate without querying
if (newProfiles.hasOwnProperty(userId)) {
newProfiles[userId][0] = 10;
} else {
newProfiles[userId] = [];
newProfiles[userId].push(1);
}
return;
}
);
return eachPromise;
}).then(function(){
var promises = [];
for (var userId in newProfiles) {
if (newProfiles.hasOwnProperty(userId)) {
var query = new Parse.Query("UserProfile");
query.equalTo("owner", userId);
var promise = query.find().then(
function (results) {
// Do something
}
);
promises.push(promise);
}
}
return Parse.Promise.when(promises);
});
The objectId in the JS SDK is given by var userId = user.id

IndexedBD and localStorage undefined error

I have an indexedDB which im trying to use to capture form information on user registration. That part is working fine but the prof wants an account to be create once with the username and password set on creation so he can log in.
The way I approached this was with a localStorage API. I created a function to check if the admin account had ever been created, and if not to create it calling the addAdmin() function.
I tried to create addAdmin() by copying my addObject() but for some reason my db variable is returning as undefined in the console.
Error" Uncaught TypeError: Cannot call method 'transaction' of undefined
var mainForm, fName, lName, uName, pass, email, dob, phone, bio, nl, terms, school, gender, save, reset, db;
//-------------USER DB------------------//
function startDB(){
mainForm = document.getElementById('mainFormSidebar');
fname = document.getElementById('fName');
lName = document.getElementById('lName');
users = document.getElementById('uName');
pass = document.getElementById('password');
email = document.getElementById('email');
dob = document.getElementById('dob');
phone = document.getElementById('phone');
bio = document.getElementById('bio');
nl = document.getElementById('newsletter');
terms = document.getElementById('terms');
school = document.getElementById('school');
gender = document.getElementsByName('gender');
save = document.getElementById('save');
reset = document.getElementById('reset');
reset.addEventListener('click',clearForm);
databox = document.getElementById('databox');
mainForm.addEventListener('submit',addObject);
//open DB
var request = indexedDB.open('macroPlay');
//if fails
request.addEventListener('error', showerror);
//if succeeds
request.addEventListener('success', start);
//if !exist, create.
request.addEventListener('upgradeneeded', createdb);
//Create Admin account on launch
chkAdmin();
}
function createdb(e){
var datababase = e.target.result;
var myusers = datababase.createObjectStore('users', {keyPath: 'userName'});
}
function start(e){
db = e.target.result;
showUsers();// Show all values in the object store
}
function addObject(){
if(confirm('Are you sure you want to resgister?')){
var fName = document.getElementById('fName').value;
var lName = document.getElementById('lName').value;
var userName = document.getElementById('uName').value;
var pass = document.getElementById('password').value;
var email = document.getElementById('email').value;
var dob = document.getElementById('dob').value;
var phone = document.getElementById('phone').value;
var bio = document.getElementById('bio').value;
var nl = document.getElementById('nl').value;
var terms = document.getElementById('terms').value;
var school = document.getElementById('school').value;
//May need to set a loop to find value of radio
var gender;
var radios = document.getElementsByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
gender=radios[i].value;
}
}
//set up transaction
var mytransaction = db.transaction(['users'], "readwrite");
//get object store
var myusers = mytransaction.objectStore('users');
//Add item
var request = myusers.add(new getUser(userName,fName,lName,pass,email,dob,phone,bio,nl,terms,school,gender));
}
// Show all results.
mytransaction.addEventListener('complete', showUsers);
//Reset Form Fields
resetForm();
}
function getUser(userName, fn, ln, pw, em, dob, tel, bio, nl,tm, scl, gender){
this.userName = userName;
this.fn = fn;
this.ln = ln;
this.pw = pw;
this.em = em;
this.dob = dob;
this.tel = tel;
this.bio = bio;
this.nl = nl;
this.tm = tm;
this.scl = scl;
this.gender = gender;
}
//------Create Admin Account-----//
function chkAdmin(){
alert('before adding admin');
if(localStorage.getItem('admin')!="added"){
alert('adding admin');
addAdmin();
alert('admin added');
}
}
function addAdmin(){
//set up transaction
var mytransaction = db.transaction(['users'], "readwrite");
//get object store
var myusers = mytransaction.objectStore('users');
var request = myusers.add(new getUser('admin','Shawn','Smith-Choa','admin'));
request.addEventListener('success',showUsers);
//Locally store that admin as been created
var admin = 'admin';
var value = 'added';
newItem(admin,value);
}
//-------------Web Storage API------------//
function newItem(id,style){
localStorage.setItem(id,style);
}
You're not assigning the value of db to anything so it's always undefined. I think you mean to be doing it in the createdb method, but really you should be capturing/assigning it in the start method which the success handler will trigger (I also can't find the start method anywhere)

how to compare the value

This my code
I am getting email address from database through ajax and mysql it is giving me value in . so in below FUNCTION comparing() i am retriving data from span to compare with the textfield data. but it is not comparing properly.
Please help me out
function validate(pageForm)
{
/************Getting error values in return values***********************/
var returncomparing = "";
/*********************************/
//FIELD WHICH YOU HAVE TO VALDATE
returncomparing += comparing(pageForm.email);
/********************************************/
if (returncomparing != "")
{
document.getElementById('error').innerHTML = returnIndustry;
}
return false;
}
After giving correct EMAIL still it is giving Error ... (Please Provide Login User ID)
function comparing(pageForm){
var error = "";
// var fetchedEmail=document.forms["pageForm"]["email_fetch"].value;
var em=document.forms["pageForm"]["email"].value;
//var emai = document.getElementById('emlTst').value;
var email = document.getElementById('txtHint').innerHTML;
//document.getElementById('emlTst').value = email;
if(em != email){
document.getElementById('error_email2').innerHTML="Please Provide Login User ID";
pageForm.style.borderColor = 'red';
error='5';
}
else if(em == email){
document.getElementById('error_email2').innerHTML="";
error = "";
}
else {
document.getElementById('error_email2').innerHTML="";
pageForm.style.borderColor = '#c7c7c7';
}
return error;
}
/*************************************************************/
var em = $('#email').val().toLowerCase();
var email = $('#txtHint').val().toLowerCase();

Categories

Resources