I have a Google Script that I've inherited and I'm looking to update it to reflect current requirements.
Currently it fires off 2 emails to a participant and sponsor using data in a Google Sheet. I've tried combining it so that section 'Now email for each doc' sends an email to the participant and cc's the sponsor.
I've gotten as far as updating the code from :
var sendTo = row[EMAIL];
to :
var sendTo = row[EMAIL] + " , " + sponsors;
and removing section '2. Personal Case' which doesn't solve the cc query.
I've tried amending the existing code to add in the additional parameters as stated on https://developers.google.com/apps-script/reference/mail/mail-app but can't seem to get it to work in the code below.
// Now email for each doc
var email = getAppraiseeEmail();
if(email && email.body) {
email.body = email.body.replaceAll('%doctitle1%', bTitle)
/*.replaceAll('%doctitle2%', pTitle)
.replaceAll('%doctitle3%', dTitle)
.replaceAll('%doctitle4%', dpTitle)
.replaceAll('%link1%', bFile.getUrl())
.replaceAll('%link2%', pFile.getUrl())
.replaceAll('%link3%', dFile.getUrl())
.replaceAll('%link4%', dpFile.getUrl())*/
.replaceAll('%link5%', child.getUrl())
.replaceAll('%name%', row[NAME]);
var sendTo = row[EMAIL];
if(sendTo && sendTo!=='') {
email.recipient = sendTo;
sendAnEmail(email);
}
} else {
throw Error('missing email configuration (Business Case)');
}
// 2. Personal Case
if(sponsors.length > 0) {
var emailRev = getSponsorEmail();
if(emailRev && emailRev.body) {
emailRev.body = emailRev.body.replaceAll('%doctitle1%', bTitle)
/*.replaceAll('%doctitle2%', pTitle)
.replaceAll('%doctitle3%', dTitle)
.replaceAll('%doctitle4%', dpTitle)
.replaceAll('%link1%', bFile.getUrl())
.replaceAll('%link2%', pFile.getUrl())
.replaceAll('%link3%', dFile.getUrl())
.replaceAll('%link4%', dpFile.getUrl()) */
.replaceAll('%link5%', child.getUrl())
.replaceAll('%name%', row[NAME]);
var sendTo = sponsors.join(',');
if(sendTo && sendTo!=='') {
emailRev.recipient = sendTo;
sendAnEmail(emailRev);
}
} else {
throw Error('missing email configuration (sponsor)');
}
} // end if re sponsors
row[NOTES] = 'Files created & shared, ' + timestamp;
} catch(e) {
console.error(e);
row[NOTES] = 'An error occurred (' + e + '), ' + timestamp;
}
function getAppraiseeEmail() {
var email = {};
email.body = getConfig('email01');
email.subject = getConfig('subject01');
return email;
}
function getSponsorEmail() {
var email = {};
email.body = getConfig('email02');
email.subject = getConfig('subject02');
return email;
}
function sendAnEmail(email) {
var options = { noReply: true, htmlBody: email.body };
MailApp.sendEmail(email.recipient, email.subject, null , options);
}
Ideally it should fire out the email from section 'Now email for each doc' and cc the sponsors in section '2. Personal Case'.
Thanks in advance!
UPDATE 15/07/19
I've updated the code to the below which now works:
// Now email for each doc
var email = getAppraiseeEmail();
if(email && email.body) {
email.body = email.body.replaceAll('%doctitle1%', bTitle)
.replaceAll('%link5%', child.getUrl())
.replaceAll('%name%', row[NAME]);
var CC = row[SPONSORS]
var sendTo = row[EMAIL]
if(sendTo && sendTo!=='') {
email.recipientTO = sendTo;
email.CC = CC;
sendAnEmail(email);
}
} else {
throw Error('missing email configuration (Business Case)');
}
row[NOTES] = 'Files created & shared, ' + timestamp;
} catch(e) {
console.error(e);
row[NOTES] = 'An error occurred (' + e + '), ' + timestamp;
}
function getAppraiseeEmail() {
var email = {};
email.body = getConfig('email01');
email.subject = getConfig('subject01');
return email;
}
function sendAnEmail(email) {
var options = { noReply: true, htmlBody: email.body, cc: email.CC };
MailApp.sendEmail(email.recipientTO, email.subject, null , options);
}
Related
I am working on a telegram bot with the node-telegram-bot-api library. I made 2 buttons using keyboard. But when you click on them a lot, the bot will spam and sooner or later it will freeze. Is it possible to somehow put a delay for the user on messages.
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
export const keyboardMain = {
reply_markup: JSON.stringify({
keyboard: [
[{
text: '/start',
},
],
resize_keyboard: true
})
};
You can create a user throttler using Javascript Map
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
How to use:
You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.
For instance I'm gonna stop the user for 10seconds once the user requests.
// global 10 second throttler
const throttle = throttler(10) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
I tried using this code, put the function code in my function file, connected everything to the required file, and I don’t understand what to do next and where to insert the last code and what to do with it. I'm new to JavaScript and just learning.
import {
bot
} from '../token.js';
import {
throttler
} from '../functions/functions.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
const throttle = throttler(10);
if (text === '/start') {
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
return bot.sendMessage(chatId, 'hello', keyboardMain);
} else {
// dont reply
}
}
return bot.sendMessage(chatId, 'error');
});
}
Get the time when he pressed the button
Get the time of the next click
Take away the difference and set the condition (if, for example, more than 3 seconds have passed between clicks, then the user will not be frozen).
var token = ""; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = ""; // FILLINYOUR GOOGLEWEBAPPADDRESS
var ssId = ""; // FILL IN THE ID OF YOUR SPREADSHEET
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e){
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var msgbegan = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A7").getValue();
var msginfo = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A9").getValue();
var answer = "%0A" + msgbegan + "%0A" ;
///////////////////////
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
// global 10 second throttler
const throttle = throttler(500) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
///////////////////////////////////////
if(text == "/start"){
sendText(id, answer);
} else if (text == "/info"){
sendText(id, msginfo);
}else{
if (text.length == 10){
var found = false;
var total_rows = SpreadsheetApp.openById(ssId).getSheets()[0].getMaxRows();
for(i=1; i<=total_rows; i++){
var loop_id = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(i,2).getValue();
if(text == loop_id){
found = true;
found_at = i; // employee row
break;
}
}
if(found){
sendText(id, work_message);
}else{
var msgerrror = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A6").getValue();
var not_found = "%0A" + msgerrror+ "%0A" ;
sendText(id, not_found);
}
} else {
sendText(id, "eroor");
}
}
/////////////
var emp_name = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,1).getValue();
var emp_work = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,3).getValue();
var homeloc = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,4).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var emp_data = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,5).getValue();
var emp_day = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,6).getValue();
var emp_clock = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,7).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var welcome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A2").getValue();
var msgemp = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A3").getValue();
var msgloc = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A4").getValue();
var msgbay = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A5").getValue();
var msghome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A8").getValue();
var msmobil = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A11").getValue();
var mstoday = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A13").getValue();
var msdata = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A14").getValue();
var msclock = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A15").getValue();
var work_message = welcome + emp_name +
"%0A" + msgemp + emp_work +
"%0A" + mstoday + emp_day +
"%0A" + msdata + emp_data +
"%0A" + msclock + emp_clock +
"%0A" + msghome + homeloc +
"%0A" + msgloc+ emp_location +
"%0A" + msgbay +
"%0A" + msmobil ;
}
Excuse me . I am a beginner
Is this the correct way
I hope to seek help from someone if possible. In the following code. Im trying to console.log() data from My Firebase reference as you can see in my code below. But the Console.log() is returning null instead of the values that are there in Firebase Realtime Database. I have also provided the code for adding which is working well. Please have a look the image of my database if it helps. I am not getting any other error in my console except the fact that this is returning null.
function addFamilyMember() {
var NameOfMember = document.getElementById("newFamilyMemberName").value;
var DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
var EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
var ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;
if (
NameOfMember.length == "" ||
DoBOfMember.length == "" ||
EmailOfMember.length == "" ||
ContactOfMember.length == ""
) {
alert("Please enter all details of your Family Member");
} else {
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
firebase
.database()
.ref("/Users/" + uid + "/Family/" + NameOfMember)
.set({
MemberName: NameOfMember,
MemberDOB: DoBOfMember,
MemberEmail: EmailOfMember,
MemberContact: ContactOfMember,
});
}
}
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
firebase
.database()
.ref("/Users/" + uid + "/Family/")
.on("value", function (snap) {
var mName = snap.child("MemberName").val();
var mDOB = snap.child("MemberDOB").val();
var mEmail = snap.child("MemberEmail").val();
var mContact = snap.child("MemberContact").val();
console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
});
The problem is you are fetching the whole Family node and trying to access data of each member.
I tried to recreate your database structure and got this in console on running the code.
{
"Name One": {"MemberContact":10000,"MemberName":"Name Two"},
"Name Two": {"MemberContact":10002,"MemberName":"Name Two"}
}
so if you want to get data of each user from that then try using forEach this way.
Object.keys(snap.val()).forEach(key => {
const memberData = snap.val()[key]
//Data of each member
var mName = memberData["MemberName"]
var mDOB = memberData["MemberDOB"]
var mEmail = memberData["MemberEmail"]
var mContact = memberData["MemberContact"]
console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
})
When loading the page for the first time, firebase.auth().currentUser shouldn't be used because Firebase Auth needs to check if the user's login session is valid first.
let currentUserFamilyRef = null;
// for use with .on("value") and .off("value")
function onValueFamilyListener(snapshot) {
const familyMembers = [];
snapshot.forEach((familyMemberSnapshot) => {
const MemberName = snap.child("MemberName").val();
const MemberDOB = snap.child("MemberDOB").val();
const MemberEmail = snap.child("MemberEmail").val();
const MemberContact = snap.child("MemberContact").val();
familyMembers.push({ MemberName, MemberDOB, MemberEmail, MemberContact });
console.log(MemberName + " " + MemberDOB + " " + MemberEmail + " " + MemberContact);
}
// TODO: do something with the array of family members familyMembers
}
// for showing loading state
function showLoadingIcon(visible) {
if (visible) {
// TODO: show the icon
// TODO: disable the submit button
} else {
// TODO: hide the icon
// TODO: enable the submit button
}
}
// for when addFamilyMember() is called while signed out
function addFamilyMemberSignedOut() {
alert('You need to sign in first!');
return false;
}
// for when addFamilyMember() is called while signed in
function addFamilyMemberSignedIn() {
const NameOfMember = document.getElementById("newFamilyMemberName").value;
const DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
const EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
const ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;
if (
NameOfMember.length == "" ||
DoBOfMember.length == "" ||
EmailOfMember.length == "" ||
ContactOfMember.length == ""
) {
alert("Please enter all details of your Family Member");
return false;
}
const user = firebase.auth().currentUser;
if (user === null) {
// shouldn't get here, but just in case.
alert('You need to sign in first!');
return false;
}
const uid = user.uid;
showLoadingIcon(true);
firebase
.database()
.ref("/Users/" + uid + "/Family/" + encodeURIComponent(NameOfMember)) // escape names as they may contain symbols, etc.
.set({
MemberName: NameOfMember,
MemberDOB: DoBOfMember,
MemberEmail: EmailOfMember,
MemberContact: ContactOfMember,
})
.then(
() => {
// saved family member's data successfully
showLoadingIcon(false);
// reset form
document.getElementById("newFamilyMemberName").value = "";
document.getElementById("newFamilyMemberDoB").value = "";
document.getElementById("newFamilyMemberEmail").value = "";
document.getElementById("newFamilyMemberContactNo").value = "";
alert('Information saved!');
},
(err) => {
// failed to save family member's data
showLoadingIcon(false);
// err.code may lead to more specific error information
console.error(err);
alert('Failed to save information!');
}
);
}
// for calling the correct addFamilyMember version
let addFamilyMember = addFamilyMemberSignedOut;
showLoadingIcon(true); // while loading the user's info, show a loading icon
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// A user is (newly/already) signed in.
// create a reference for this user's family
const newUserFamilyRef = firebase.database()
.ref("/Users/" + user.uid + "/Family");
if (currentUserFamilyRef !== null) {
// if the old user and new user are the same, do nothing
// but if they've changed, remove the old listener and update currentUserFamilyRef
if (!currentUserFamilyRef.isEqual(newUserFamilyRef)) {
currentUserFamilyRef.off("value", onValueFamilyListener);
currentUserFamilyRef = newUserFamilyRef;
}
} else {
currentUserFamilyRef = newUserFamilyRef;
}
// use the "signed in" version of addFamilyMember
addFamilyMember = addFamilyMemberSignedIn;
// attach listener to "/users/{user.uid}/Family"
currentUserFamilyRef.on("value", onValueFamilyListener);
} else {
// no user is signed in.
// use the "not signed in" version of addFamilyMember
addFamilyMember = addFamilyMemberSignedOut;
// if a user was logged in, clean up it's listener to prevent errors
if (currentUserFamilyRef !== null) {
currentUserFamilyRef.off("value", onValueFamilyListener);
}
// no user, so set the reference to null
currentUserFamilyRef = null;
}
showLoadingIcon(false);
});
You can't directly use firebase.auth().currentUser. First you need to check the authentication state of the user. Then only you can ask for the current user. So to do this you need to wrap it using authentication state observer.You can read more about it on firebase documentation: [https://firebase.google.com/docs/auth/web/start][1]
function addFamilyMember() {
var NameOfMember = document.getElementById("newFamilyMemberName").value;
var DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
var EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
var ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
if (
NameOfMember.length == "" ||
DoBOfMember.length == "" ||
EmailOfMember.length == "" ||
ContactOfMember.length == ""
) {
alert("Please enter all details of your Family Member");
} else {
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
firebase
.database()
.ref("/Users/" + uid + "/Family/" + NameOfMember)
.set({
MemberName: NameOfMember,
MemberDOB: DoBOfMember,
MemberEmail: EmailOfMember,
MemberContact: ContactOfMember,
});
}
}
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
firebase
.database()
.ref("/Users/" + uid + "/Family/")
.on("value", function (snap) {
var mName = snap.child("MemberName").val();
var mDOB = snap.child("MemberDOB").val();
var mEmail = snap.child("MemberEmail").val();
var mContact = snap.child("MemberContact").val();
console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
})
})}
In my Node application I have used get and post request. Using get just renders the page and using post insert data into MySQL database. Data is inserted properly but after post gets called and alert fade away very quickly.
This is my code from app.js:
app.get('/Associate', routes.Associate);
app.get('/addAssociate',routes.addAssociate);
app.post('/addAssociate',routes.postAssociate);
This is my code from routes.js:
Associate: function(req, res) {
sess = req.session;
var name = req.session.user;
var username = 'SELECT first_name from user_info where email_id=?';
if (sess.user) {
console.log('\n--------------------- Associate ----------------------');
var db = req.app.get('db')();
var id = req.query['id'];
// var newsquery='SELECT * from associate_info';
var assoquery = 'SELECT associate_id,doctor_id,CONCAT(initial," ",first_name," ",middle_name," ",last_name) As Name,qualification,address_line1,city,state,pincode,email_id,contact_no from associate_info ';
var redirect = 'Associate_Listing';
async.parallel({
one: function(callback) {
db.query(assoquery, function(error, rows, fields, next) {
console.log("length-\t", rows.length);
callback(error, rows);
});
},
two: function(callback) {
db.query(username, [name], function(error, rows, fields, next) {
// console.log(rows.length);
console.log(rows);
callback(error, rows);
});
}
},
function(error, results) {
var totalNews = results.one.length;
for (var i = 0; i < results.one.length; i++) {
if (!(results.one[i].views > 0) || results.one[i].views == null)
results.one[i].views = 0;
results.one[i].ids = i + 1;
// if(!(results.one[i].views>0))
// results.one[i].views=0;
}
// console.log("--------",results.one[0].id);
res.render(redirect, {
error: JSON.stringify(1),
from_period: 0,
to_period: 0,
state: JSON.stringify("All States"),
user2: "Dr" + " " + JSON.parse(JSON.stringify(results.two[0]["first_name"])),
user: JSON.parse(JSON.stringify(req.session.user)),
Associate: results.one,
str_journal: JSON.stringify(results.one),
user_type_id: req.session.user_type_id,
totalJournals: JSON.stringify(totalNews)
});
});
} else {
res.redirect('/login');
}
},
// addJournal:function(req,res){
addAssociate: function(req, res) {
console.log('\n-------------------- addAssociate ----------------------\n');
var name = req.session.user;
var db = req.app.get('db')();
var username = 'SELECT first_name from user_info where email_id=?';
if (req.session.user) {
async.parallel({
one: function(callback) {
db.query(username, [name], function(error, rows, fields, next) {
console.log("length-\t", rows.length);
callback(error, rows);
});
}
},
function(error, results) {
res.render('addAssociate', {
user: JSON.parse(JSON.stringify(req.session.user)),
// cases : results.one,
user2: "Dr" + " " + JSON.parse(JSON.stringify(results.one[0]["first_name"])),
user_type_id: req.session.user_type_id,
// totalNews :JSON.stringify(totalNews)
})
});
} else {
res.redirect('/login');
// res.redirect('addAssociate');
}
},
postAssociate: function(req, res) {
console.log('\n-------------------- postAssociate ----------------------\n');
var db = req.app.get('db')();
// res.send('Username: ' + req.body.doctorName);
// var title = req.body.title;
// var created =req.body.created;
// initial : req.body.doctorName,
// var id=1;
// var dateArray=created.split('/');
// var finalDate=""+dateArray[2]+"/"+dateArray[1]+"/"+dateArray[0];
// var date1=new Date(finalDate);
var initial;
var first_name;
var middle_name;
var last_name;
var qualification;
var address_line1;
var address_line2;
var city;
var state;
var pincode;
var email_id;
var contact_no;
var Uname = req.session.user;
var post = {
initial: req.body.initial,
first_name: req.body.first_name,
middle_name: req.body.middle_name,
last_name: req.body.last_name,
qualification: req.body.qualification,
address_line1: req.body.address_line1,
address_line2: req.body.address_line2,
city: req.body.city,
state: req.body.state,
pincode: req.body.pincode,
email_id: req.body.email_id,
contact_no: req.body.contact_no,
status: 1,
};
console.log('--------------------' + initial)
console.log(initial);
console.log(post);
db.query('SELECT * from user_info where email_id= ? ', [Uname], function(error, rows, fields) {
if (error) {
console.log(error);
} else {
console.log('name------------' + Uname);
console.log('rows---------' + rows.length);
for (var i in rows) {
console.log('----------hhh---' + rows[i].doctor_id);
}
db.query('INSERT INTO associate_info SET doctor_id=' + rows[i].doctor_id + ', creation_date=CURRENT_TIMESTAMP(), ? ', post, function(error, result) {
console.log('inside if');
if (error) {
console.log(error);
res.status(200).send({
success: 3,
error: error
});
return;
}
console.log('Associate added successfully.');
});
}
});
},
this is jquery ajax code
$(document).ready(function() {
$("#save").click(function() {
var initial = $("#doctorName").val();
var first_name = $("#firstName").val();
var middle_name = $("#middleName").val();
var last_name = $("#lastName").val();
var qualification = $("#qualification").val();
var address_line1 = $("#address1").val();
var address_line2 = $("#address2").val();
var city = $("#city").val();
var state = $("#state").val();
var pincode = $("#pincode").val();
var email_id = $("#email").val();
var contact_no = $("#mobile").val();
var dr = /^[a-zA-Z]+\.$/;
var alphaExp = /^[a-zA-Z]+$/;
var zipexp = /^[0-9]{1,6}$/;
var mobileexp = /^(\+91-|\+91|0)?\d{10}$/;
var emailexp = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*#[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'initial=' + initial + '&first_name=' + first_name + '&middle_name=' + middle_name + '&last_name=' + last_name + '&qualification=' + qualification + '&address_line1=' + address_line1 + '&address_line2=' + address_line2 + '&city=' + city + '&state=' + state + '&pincode=' + pincode + '&email_id=' + email_id + '&contact_no=' + contact_no;
if (initial == '' || first_name == '' || middle_name == '' || last_name == '' || qualification == '' || address_line1 == '' || address_line2 == '' || city == '' || state == '' || pincode == '' || email_id == '' || contact_no == '') {
alert("Please Fill All Mandatory Fields");
return false;
} else if (!initial.match(alphaExp) && !initial.match(dr)) {
alert("please insert valid initial");
$("#doctorName").val('');
document.getElementById('doctorName').focus();
return false;
} else if (!first_name.match(alphaExp)) {
alert("please insert valid first name");
$("#firstName").val('');
document.getElementById('firstName').focus();
return false;
} else if (!middle_name.match(alphaExp)) {
alert("please insert valid middle name");
$("#middleName").val('');
document.getElementById('middleName').focus();
return false;
} else if (!last_name.match(alphaExp)) {
alert("please insert valid last name");
$("#lastName").val('');
document.getElementById('lastName').focus();
return false;
} else if (!pincode.match(zipexp) || pincode.length != 6) {
alert("please insert valid pincode");
$("#pincode").val('');
document.getElementById('pincode').focus();
return false;
} else if (!email_id.match(emailexp)) {
alert("please insert email id");
$("#email").val('');
document.getElementById('email').focus();
return false;
} else if (!contact_no.match(mobileexp)) {
alert("please insert valid contact no");
$("#mobile").val('');
document.getElementById('mobile').focus();
return false;
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "post",
url: "/addAssociate",
// contentType: 'application/json',
data: dataString,
cache: false,
success: function(data) {
console.log("data-----------" + data);
alert("hi");
}
});
}
// return;
// return false;
});
});
I want to display an alert after data inserted successfully into database.
Just Try the Following to make some delay.
jQuery :
$.ajax({
url:'path-to-process',
type:'POST',
data:{},
success:function(){
// Content to Display on Success.
setTimeout(function () {
// Content to Display on Success with delay.
}, 800);
}
});
Here, the "setTimeout()" will provide some specified time delay for display your content.
Have a Nice Day !
http://jsbin.com/jatuju/edit?js,output
If you are using the plan old JavaScript,you can using the XMLHttpRequest status code to determine whether is success or not
I'm having a problem locating where my problem is. I'm using PubNub for realtime messaging and the example project is using ECC (elliptical curve cryptography) encrypted messaging.
Every thing in the file works(animation, channel presence, etc.) except for sending the message. Every time I hit send I get this message:
Here is my chat-app.js file:
(function() {
if (typeof(user) === 'undefined') {
return;
}
var output = document.getElementById('output'),
input = document.getElementById('input'),
picture = document.getElementById('picture'),
presence = document.getElementById('presence'),
action = document.getElementById('action'),
send = document.getElementById('send');
var channel = 'fun';
var keysCache = {};
var pubnub = PUBNUB.init({
subscribe_key: 'sub-c-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
publish_key: 'pub-c-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
uuid: user.name,
auth_key: user.gtoken,
ssl: true
});
function displayOutput(message) {
if(!message) return;
if(typeof(message.text) === 'undefined') return;
var html = '';
if ('userid' in message && message.userid in keysCache) {
var signature = message.signature;
delete message.signature;
var result = ecc.verify(keysCache[message.userid].publicKey, signature, JSON.stringify(message));
if(result) {
html = '<p><img src="'+ keysCache[message.userid].picture +'" class="avatar"><strong>' + keysCache[message.userid].name + '</strong><br><span>' + message.text + '</span></p>';
} else {
html = '<p><img src="images/troll.png" class="avatar"><strong></strong><br><em>A troll tried to spoof '+ keysCache[message.userid].name +' (but failed).</em></p>';
}
output.innerHTML = html + output.innerHTML;
} else {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/user/' + message.userid, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var res = JSON.parse(xhr.responseText);
keysCache[message.userid] = {
'publicKey': res.publicKey,
'name': res.name,
'artist': res.artist,
'picture': res.picture,
'id': res.id
}
displayOutput(message);
}
};
xhr.send(null);
}
}
function getHistory() {
pubnub.history({
channel: channel,
count: 30,
callback: function(messages) {
messages[0].forEach(function(m){
displayOutput(m);
});
}
});
}
pubnub.subscribe({
channel: channel,
restore: true,
connect: getHistory,
disconnect: function(res){
console.log('disconnect called');
},
reconnect: function(res){
console.log('reconnecting to pubnub');
},
callback: function(m) {
displayOutput(m);
},
presence: function(m){
if(m.occupancy === 1) {
presence.textContent = m.occupancy + ' person online';
} else {
presence.textContent = m.occupancy + ' people online';
}
if((m.action === 'join') || (m.action === 'timeout') || (m.action === 'leave')){
var status = (m.action === 'join') ? 'joined' : 'left';
action.textContent = m.uuid + ' ' + status +' room';
action.classList.add(m.action);
action.classList.add('poof');
action.addEventListener('animationend', function(){action.className='';}, false);
}
}
});
function post() {
var safeText = input.value.replace(/\&/g, '&').replace( /</g, '<').replace(/>/g, '>');
var message = { text: safeText, userid: user.id };
var signature = ecc.sign(user.eccKey, JSON.stringify(message));
message['signature'] = signature;
pubnub.publish({
channel: channel,
message: message
});
input.value = '';
}
input.addEventListener('keyup', function(e) {
if(input.value === '') return;
(e.keyCode || e.charCode) === 13 && post();
}, false);
send.addEventListener('click', function(e) {
if(input.value === '') return;
post();
}, false);
})();
This error is coming from my ecc.js file
Uncaught TypeError: Cannot read property 'r' of undefined
However, I'm assuming the error is in the chat-app.js file because I didn't touch the ecc.js file. I got it from the project -- https://github.com/pubnub/auth-chat-demo
More info on ECC can be found here: https://github.com/jpillora/eccjs
According to your description, it looks like this line is giving you the error:
var signature = ecc.sign(user.eccKey, JSON.stringify(message));
So I am guessing you are not properly passing user.eccKey?
Do you have all the user data from oAuth (or any login auth)? or is the eccKey generated correctly upon the user sign-up?
Also, try include the non-minified version of ecc.js so you can track where the error is coming from more easily.
https://raw.githubusercontent.com/jpillora/eccjs/gh-pages/dist/0.3/ecc.js
I'm making a register/login form in javascript. User should enter information about himself and the computer should put that information into an array and remember it but it 'forgets' it every time I reload the page.
else {
document.cookie = email;
cookies[cookies.length] = document.cookie;
$('#error').text("Your registration is complete.");
break;
}
...more code
$('.btn').click(function() {
alert(cookies[cookies.length - 1]);
});
Any ideas to solve this? I have one more question. How can I check weather is an username alerady in use?
Here is the full js code:
var main = function() {
var people = [];
var cookies = [];
$('#register_email').val("");
$('#register_username').val("");
$('#register_password').val("");
$('#register2_password').val("");
function Person(username, email, password, repeat_password) {
this.username = username;
this.email = email;
this.password = password;
this.repeat_password = repeat_password;
}
$('#register').click(function() {
var username = $('#register_username').val();
var email = $('#register_email').val();
var password = $('#register_password').val();
var r_password = $('#register2_password').val();
if( email==="" || username==="" || password==="" || r_password==="") {
$('#error').text("You didn't fill everything");
}
else {
people[people.length] = new Person(username, email, password, r_password);
for(var key in people) {
//This should check weather this username was used before but I'm not really sure what to insert instead of "name"
if(people[people.length - 1].username === "name") {
$('#error').text("This username is already in use");
break;
}
else if(password !== r_password) {
$('#error').text("Passwords don't match");
break;
}
else {
document.cookie = email;
cookies[cookies.length] = document.cookie;
$('#error').text("Your registration is complete.");
break;
}
}
}
});
$('.btn').click(function() {
alert(cookies[cookies.length - 1]);
});
};
$(document).ready(main);
There is a js-fiddle live example in comments.