How to display alert after AJAX post success.alert? - javascript

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

Related

How do I add an email cc into my Google Script

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);
}

Unable to make asynchronous HTTP call in Angular with Laravel framework

I'm facing a very strange issue where I'm able to make asynchronous HTTP call in my local Cent-OS environment but as soon as I push my code to demo server somehow the HTTP calls are not executed asynchronously.
Below is the function that I'm trying to execute,
$scope.getResults = function(){
$http({
url: /getResults,
method: 'POST',
data: data,
headers: {'async': true}
})
.then(function (response) {
var contactId = response.data.contactId[0];
$scope.loadProfileInfo(contactId);
var requestId = response.data.requestId;
$scope.getTotalCount(requestId);
}
});
};
$scope.loadProfileInfo = function(id){
$http({
url: /getProfileInfo,
method: 'POST',
data: {contactId: id},
headers: {'async': true})
.then(function (response) {
//perform operations
});
};
$scope.getTotalCount = function(id){
$http({
url: /getTotalCount,
method: 'POST',
data: {some: data},
headers: {'async': true})
.then(function (response) {
//perform operations
});
};
When I call the function getResults() it loads the results and calls the function loadProfileInfo() which loads the profile information as expected.
Now the issue is the function getTotalCount takes a lot longer to execute and until it does not return the response no other HTTP calls are processed even if they are very small.
I'm using Laravel PHP framework.
Real Code
Reference:
pageChangeHandler() = getResults()
getCount() = getTotalCount()
showProfileAction() = loadProfileInfo()
$scope.pageChangeHandler = function(num) {
$scope.checkMoreResults = false;
console.log("pageChangeHandler begins");
//removing cached values from previous results
$("#analyticsResults").text("...");
$scope.showTitleLevelGraph(['','','','',''], [0,0,0,0,0]);
$scope.showScoreGraph([0,0,0,0,0,0]);
$scope.showGenderGraph([0,0,0]);
$scope.showCompanySizeGraph([0,0,0,0]);
$scope.analyticsFlag = false;
$("#loading-bar").show();
$("#loading-spinner").show();
if ($window.Math.ceil(num*50)>50000){
sweetAlert("Oops", "Seeking is limited to 50,000 results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
} else {
$('body').css('cursor', 'progress');
// if downloadList exists, save it so it can be added to after reloading.
if ($scope.downloadList.length>0) {
$scope.storedSelectedContacts = angular.copy($scope.downloadList);
$scope.storedLiUrl = angular.copy($scope.liUrl);
$scope.storedCompanyName = angular.copy($scope.companyName);
$scope.storedCompLink = angular.copy($scope.compLink);
}
$scope.selectedPage = num;
//$scope.showProfile = false;
//$scope.profileData = null;
if (num > 1 || null!==$scope.shortCode) {
// use code
var data = {'code': $scope.shortCode};
} else {
$scope.shortCode = null;
var data = angular.copy($scope.wizardData);
console.debug(data+" "+JSON.stringify(data));
try{
if (data.state.length > 0) {
for (var x = 0; x < data.state.length; x++) {
data.tbl_company_State[x] = data.state[x].value;
}
data.state = null; // null it out to prevent issues in LV controller
}
}catch(e){
}
}
//console.debug(data);
if ($scope.searchFast == true){
var url = $scope.baseUrl + "/search/fast?page=" + num;
} else {
var url = $scope.baseUrl + "/search/wizard?page=" + num;
console.log("wizard: "+num);
var newsearch = true;
}
console.log("Real data: "+JSON.stringify(data));
$http({
url: url,
method: 'POST',
data: data,
headers: {'async': true}
})
.success(function (response) {
(function() {
setTimeout(function() {
// code-here
//response = response.data;
console.log("Search results: "+JSON.stringify(response));
$('body').css('cursor', 'auto');
//console.debug(response);
if (response.error){
if (response.error == 1000000) {
sweetAlert("Oops", "Your search returned more than 1 million results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
$scope.totalResults = '1000000+';
} else {
sweetAlert("Oops", response.error, "error");
$scope.totalResults = '0';
}
} else {
if (response.data) {
//loading the profile of the first result from the fast load
$scope.selectedAll = false;
$scope.searchResults = response.data;
$scope.totalResults = response.total;
$scope.resultStart = $window.Math.ceil((response.per_page * response.current_page) - response.per_page + 1);
$scope.resultEnd = $window.Math.ceil(response.per_page * response.current_page);
if ($scope.resultEnd > $scope.totalResults) {
$scope.resultEnd = angular.copy($scope.totalResults);
}
$scope.resultsPerPage = response.per_page;
$scope.pageSize = $scope.resultsPerPage;
$scope.lastPage = response.last_page;
$scope.currentPage = response.current_page;
if (response.code) {
$scope.shortCode = response.code;
$scope.disableRange = false;
}
$scope.shareUrl = $scope.baseUrl + '/search/code/' + $scope.shortCode;
console.log();
if (response.data.length > 0) {
if ($scope.currentPage > 1 && $scope.passedCode!='') {
$scope.passedCode=''
}
if ($scope.currentPage == 1 && ($scope.searchFast==true || $scope.searchFast==null)) {
//------Edit Jeet kapadia---//
if($scope.newSearchFlag == false){
$scope.showResults = true;
//loading the profile of the first result from the fast load
$scope.firstContactId = response.data[0].ContactID;
console.log("1 Profile loaded");
$scope.showProfileAction($scope.firstContactId);
}
}*/
//-----End Jeet Kapadia-----//
}
if(newsearch == true && $scope.newSearchFlag == true){
//console.log(response.data[0]);
//$scope.newSaveSelectSearch();
$scope.showResults = false;
newsearch = "false";
}
angular.forEach($scope.searchResults, function (item) {
item.Selected = false;
if (arrayObjectIndexOf($scope.storedSelectedContacts, item.ContactID)>-1 || arrayObjectIndexOf($scope.downloadList, item.ContactID)>-1) {
item.Selected = true;
}
});
$scope.buildDownloadList();
if (response.more){
$scope.totalResults = 'Loading...';
$scope.searchFast=false;
$scope.disableRange = true;
$scope.checkMoreResults = true;
$scope.pageChangeHandler(1);
}else{
$scope.getCount();
//reloading the profile of the first result if the contact changes after all
//the records have been loaded
if($scope.firstContactId != response.data[0].ContactID){
console.log("2 Profile loaded: "+$scope.firstContactId+" "+response.data[0].ContactID);
$scope.showProfileAction(response.data[0].ContactID);
}
//fetching all results to perform analytics on
console.log("short code: "+$scope.shortCode);
//globalAnalyticsInterval = $interval(function () {
}
} else {
sweetAlert("Oops", "Your search returned 0 results. Please widen your search parameters a bit.", "error");
}
}
}
}, 500)
})()
});
}
};
$scope.getCount = function(){
var data = angular.copy($scope.wizardData);
console.debug(data+" "+JSON.stringify(data));
try{
if (data.state.length > 0) {
for (var x = 0; x < data.state.length; x++) {
data.tbl_company_State[x] = data.state[x].value;
}
data.state = null; // null it out to prevent issues in LV controller
}
}catch(e){
}
var url = $scope.baseUrl + "/search/getCount";
$http.post(url, data)
.success(function (response) {
//response = response.data;
$scope.lastPage = response.last_page;
$scope.totalResults = response.total;
console.log("Count: "+JSON.stringify(response));
});
};
$scope.showProfileAction = function(id) {
$scope.liTimeoutFlag = false;
$scope.liResponseFlag = false;
$scope.storedContactId = id;
console.log("showProfileAction: "+id);
$scope.showProfile = false;
$scope.profileData = null;
$("#qualityScoreText").text("Verifying");
$scope.socialScoreFlag = false;
$scope.emailScoreFlag = false;
$("#profileInfo").addClass("visibilityHidden");
try{
$scope.canceller.resolve();
}catch(err){
//console.log("showProfileAction: "+err.message);
}
$scope.userNoteContactId = id;
//getting user notes for the contact
$scope.getUserNoteComment(id);
//console.debug(id);
if (id > 0) {
$scope.idContactSelected = id;
var url = $scope.baseUrl + "/search/contact/" + id;
$('body').css('cursor', 'progress');
$('#profilePanel').css('background-color: #ccc');
$http.get(url)
.then(function (response) {
response = response.data;
$('body').css('cursor', 'auto');
$('#profilePanel').css('background-color: #fff');
if (response.error) {
sweetAlert("Oops", "Contact info could not be loaded.", "error");
} else {
if (response.id) {
if ($scope.mapMarker!==null) {
$scope.mapMarker.setMap(null);
}
$timeout(function(){
$scope.showProfile = true;
}, 100)
$scope.profileData = response;
$("#profileInfo").removeClass("visibilityHidden");
$scope.lat = parseFloat($scope.profileData.Latitude).toFixed(6);
$scope.lon = parseFloat($scope.profileData.Longitude).toFixed(6);
$scope.mapOptions = {
zoom: 14,
center: new google.maps.LatLng($scope.lat, $scope.lon),
// Style for Google Maps
styles: [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}],
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.mapMarker = new google.maps.Marker({
map: $scope.myMap,
position: $scope.mapOptions.center
});
for(var key in $scope.profileData) {
//console.log(key+" "+$scope.profileData[key]);
}
//verifying the email address of the loaded profile
var emailUrl = $location.protocol() + '://'+ $location.host() + '/contact/verify/' + id;
$http.post(emailUrl)
.then(function (result) {
var singleVerificationKey = result.data.verification_key;
var emailStatus = result.data.status;
var singleEmailResult = result.data.result;
console.log("single email call: "+JSON.stringify(result)+" "+emailStatus);
if($scope.storedContactId == result.data.contactid){
if(emailStatus == "0"){ //when something goes wrong while verifying the email
$("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
}else if(emailStatus == "2"){ //when the email is verified in last 24 hours
if((singleEmailResult == 'pass')){ //success
$("#qualityScoreEmail").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact IS up to date.'></i> Email");
}else if((singleEmailResult == 'fail')){ //failed
$("#qualityScoreEmail").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is NOT up to date.'></i> Email");
}else if((singleEmailResult == 'unknown')){ // unknown
$("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
}
}else if(emailStatus == "1"){
console.log("single email key: "+singleVerificationKey);
//instantiate a Pusher object with our Credential's key
var pusher = new Pusher('2703a05dc7f552e2a2d5', {
encrypted: true
});
//Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe(singleVerificationKey);
//Bind a function to a Event (the full Laravel class)
channel.bind('EmailSingleVerification', $scope.singleEmailVerification);
}
}else{
console.log("single email creation information from previous request");
}
});
// //verifying the social information of the loaded profile
var liUrl = $scope.baseUrl + '/socialVerifyBatch';
var contactIdArr = [id];
var postData = {'id': contactIdArr, 'background': false};
$http.post(liUrl, postData)
.then(function (result) {
setTimeout(function () {
console.log("Timeout: start");
$scope.liTimeoutFlag = true;
if(($scope.storedContactId == result.data.contactid) && (!$scope.liResponseFlag)){
console.log("Timeout: making unknown");
$("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
$scope.animateScore($scope.profileData.Quality_Score, $scope.profileData.Quality_Score-1, 1000);
console.log("here 1");
var url = $scope.baseUrl + '/contact/verifySocial/' + $scope.storedContactId + "/6";
$http.post(url)
.then(function (result) {
console.log("Timeout: Update quality score: "+JSON.stringify(result));
}
);
}
}, 20000);
console.log("single li: "+JSON.stringify(result)+" "+$scope.storedContactId+" "+result.data.contactid);
if($scope.storedContactId == result.data.contactid){
//if the social information was verified in last 24 hours
if(result.data.status == "exist"){
if(result.data.passed == 1){ //success
$("#qualityScoreSocial").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact IS up to date.'></i> Social");
}else if(result.data.failed == 1){ //failed
$("#qualityScoreSocial").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is NOT up to date.'></i> Social");
}else if(result.data.unknown == 1){ // unknown
$("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
}
}else if(result.data.status == "done"){
var uniqueString = result.data.download_key;
console.log("karthik key: "+uniqueString);
//instantiate a Pusher object with our Credential's key
var pusher = new Pusher('2703a05dc7f552e2a2d5', {
encrypted: true
});
//Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe(uniqueString);
//Bind a function to a Event (the full Laravel class)
channel.bind('SocialBulkVerification', $scope.singleSocialVerification);
console.log("end karthik key");
}
}else{
console.log("single social creation information from previous request");
}
});
}
}
});
} else {
}
}
Any help is appreciated. Thanks in advance.

TypeError: Cannot read property 'toString' of undefined - why?

Here is the line (50) where this is happening:
var meetingId = meeting._id.toString(),
And here is the full, relevant code:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var config = require('./config'),
xlsx = require('./xlsx'),
utils = require('./utils'),
_ = require('lodash'),
url = config.DB_URL;
var meetings = [];
function findNumberOfNotesByMeeting(db, meeting, callback) {
var meetingId = meeting._id.toString(),
meetingName = meeting.name.displayValue,
attendees = meeting.attendees;
host = meeting.host;
var count = 1, pending = 0, accepted = 0;
console.log("==== Meeting: " + meetingName + '====');
_.each(attendees, function(item) {
console.log(count++ + ': ' + item.email + ' (' + item.invitationStatus + ')');
if (item.invitationStatus == 'pending') { pending++; }
else if (item.invitationStatus == 'accepted') { accepted++; }
});
console.log("*** " + attendees.length + ", " + pending + "," + accepted);
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, doc) {
var emails = [];
if (doc.emails) {
doc.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
db.collection('notes').find({ 'meetingId': meetingId }).count(function(err, count) {
if (count != 0) {
console.log(meetingName + ': ' + count + ',' + attendees.length + ' (' + email + ')');
meetings.push([ meetingName, count, email, attendees.length, pending, accepted ]);
}
callback();
});
}
});
}
function findMeetings(db, meeting, callback) {
var meetingId = meeting._id.toString(),
host = meeting.host;
db.collection('users').findOne({'_id': new ObjectId(host)}, function(err, doc) {
var emails = [];
if (!err && doc && doc.emails) {
doc.emails.forEach(function(e) {
emails.push(e.email + (e.primary ? '(P)' : ''));
});
}
var email = emails.join(', ');
if (utils.toSkipEmail(email)) {
callback();
} else {
db.collection('notes').find({ 'meetingId': meetingId }).count(function(err, count) {
if (count != 0) {
var cursor = db.collection('meetings').find({
'email': {'$regex': 'agu', '$options': 'i' }
});
}
callback();
});
}
cursor.count(function(err, count) {
console.log('count: ' + count);
var cnt = 0;
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
findNumberOfNotesByMeeting(db, doc, function() {
cnt++;
if (cnt >= count) { callback(); }
});
}
});
});
});
}
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findMeetings(db, function() {
var newMeetings = meetings.sort(function(m1, m2) { return m2[1] - m1[1]; });
newMeetings.splice(0, 0, [ 'Meeting Name', 'Number of Notes', 'Emails' ]);
xlsx.writeXLSX(newMeetings, config.xlsxFileNameMeetings);
db.close();
});
});
As you can see, the meeting variable (which I am almost 100% sure is the problem, not the _id property) is passed in just fine as a parameter to the earlier function findNumberOfNotesByMeeting. I have found some information here on SO about the fact that my new function may be asynchronous and needs a callback, but I've attempted to do this and am not sure how to get it to work, or even if this is the right fix for my code.
You're not passing the meeting object to findMeetings, which is expecting it as a second parameter. Instead of getting the meeting object, the function receives the callback function in its place, so trying to do meeting._id is undefined.
In fact, what is the purpose of the findMeetings function? It's name indicates it can either find all meetings in the database, or all meetings with a specific id. You're calling it without a meeting id indicating you might be trying to find all meetings, but its implementation takes a meeting object. You need to clear that up first.

Function within function want to execute very first function completely

I got a problem.I have multiple callback functions .
Function within function within a loop
I want to execute very first function fully first . Then I want to move further.
Currenlty no function is working fine:
function recurring_end() {
var diffbot = new Diffbot('ddddd');
var sql= "SELECT `bookmarks`.`id`,`bookmarks`.`bookmark_url` as url FROM bookmarks LIMIT 0, 10";
connection.query(sql, function(err,bookmarks) {
console.log(JSON.parse(JSON.stringify(bookmarks)));
for(var i = 0; i< bookmarks.length; i++){
(function(i) {
bookmark_id = bookmarks[i].id;
bookmark_url = bookmarks[i].url;
parseArticle(i,bookmark_id,bookmark_url,function(err,result){
bookamrk_title= result.bookmark_title;
bookmark_body= result.body;
bookmark_file_name= result.file_name;
preview_image = result.preview_image;
local_image_name = result.local_image_name;
mainPreviewImage = result.mainPreviewImage;
viewImage=result.viewImage;
var mediaExist =result.mediaExist;
if(mediaExist == 1) {
console.log("Entered in Media Exist");
download(preview_image, "images/" + local_image_name, function() {
console.log("Entered in download");
fs.exists("images/" + local_image_name, function(exists) {
console.log("Before Sending " +mainPreviewImage);
console.log("Before Sending Local " +local_image_name);
ImageMagic(local_image_name,mainPreviewImage,223,147,function(err,result) {
if(result != 0){
mainPreviewImage= result;
console.log("Image Magic Done" +mainPreviewImage);
AmazonUpload(mainPreviewImage,function(err,result) {
console.log("Amazon error "+err);
if(result != 0){
mainPreviewImage = result;
console.log("First Image Uploading is Sucessfully");
/* Now Lets Pass View Image FROM Graphic Magic */
ImageMagic(mainPreviewImage,viewImage,152,100,function(err,result) {
if(result != 0){
viewImage= result;
/* Upload New View File to Amazon */
AmazonUpload(viewImage,function(err,result) {
if(result != 0){
viewImage = result;
console.log("Second Image Upload to Amazon");
/*Finally here we need to write update logic here check it out */
console.log("Serious id is "+i);
console.log("Book Mark id " +bookmark_id);
console.log("bookamrk_title" +bookamrk_title);
console.log("preview_image"+mainPreviewImage);
console.log("viewImage"+viewImage);
console.log("End " +ddd);
}else {
/* need to write update Query here */
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else{
/* need to write update Query here */
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else {
/* need to writeUpdate Query Here */
var mainPreviewImage= 'default_bookmark.png';
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else{
/* need to write Update Query here */
var mainPreviewImage= 'default_bookmark.png';
var viewImage="thumbnail_default_bookmark1.png";
}
});
});
});/* download function closed */
}
});
})(i);
}
console.log("Every Thing is done ");
});
}
function AmazonUpload(uploadImage,callback) {
knox.putFile('images/'+uploadImage,'BookmarkPreviewImages/'+uploadImage, {"Content-Type": "image/jpeg",'x-amz-acl': 'public-read'}, function (err, result) {
if(!err){
if(result.statusCode==200){
callback(err,uploadImage);
}else{
callback(err,0);
}
}else{
callback(err,0);
}
});
}
function download(uri, filename, callback) {
request.head(uri, function(err, res, body) {
//request(uri).pipe(fs.createWriteStream(filename),{end:true}).on('close', callback);
var r = request(uri);
r.pause()
r.on('response', function (resp) {
if(resp.statusCode === 200){
r.pipe(fs.createWriteStream(filename),{end:true}).on('close', callback); //pipe to where you want it to go
r.resume()
}
});
});
};
function ImageMagic(local_image_name,display_image,width,height,callback){
console.log("local_image_name is"+local_image_name);
gm('images/'+local_image_name).resize(width, height, '^').gravity('Center').crop(width, height).write('images/'+display_image, function (err) {
if(!err){
console.log("Sucessfully Image converted is "+display_image);
console.log("Sucessfully image which is converted "+ local_image_name);
callback(null,display_image);
}else{
console.log("Graphic Magic Error "+err);
callback(err,0);
}
});
}
function parseArticle(i,bookmark_id,bookmark_url,callback) {
diffbot.article({uri: bookmark_url}, function(err, response) {
var callBackString= {};
console.log("Diffbot Parsing URL with id " +bookmark_id+"and loop id is"+i);
var bookmark_title = response.title;
var body = response.html;
var timestamp = new Date().getTime().toString();
var file_name = common_function.generateRandomString() + timestamp + '.txt';
var timestamp0 = new Date().getTime().toString();
var local_image_name = common_function.generateRandomString() + timestamp0 + i + '.jpg';
var preview_image = response.media[0]['link'];
if(response.media[0].primary=='true'){
mainPreviewImage = "thumb_" + local_image_name;
viewImage = "thumbnail_" + local_image_name;
mediaExist=1;
}else{
mainPreviewImage="default_bookmark.png";
viewImage="thumbnail_default_bookmark1.png";
mediaExist=0;
}
callBackString .bookmark_title=bookmark_title;
callBackString.body = body;
callBackString.file_name = file_name;
callBackString.preview_image = preview_image;
callBackString.local_image_name = local_image_name;
callBackString.mainPreviewImage = mainPreviewImage;
callBackString.viewImage=viewImage;
callBackString.mediaExist =mediaExist;
callback(null,callBackString);
});
};
I understand the code is too long. I want to get an idea, I want to execute i=0 first completely, then I want to proceed further.
Any Idea how we can do in Nodejs. Any Help Will be appreicated
Thanks
Try replacing the loop with a recursive code like this..
function recurring_end() {
var diffbot = new Diffbot('ddddd');
var sql= "SELECT `bookmarks`.`id`,`bookmarks`.`bookmark_url` as url FROM bookmarks LIMIT 0, 10";
connection.query(sql, function(err,bookmarks) {
console.log(JSON.parse(JSON.stringify(bookmarks)));
var i = 0;
var callbackForParseArticle = function(err,result){
bookamrk_title= result.bookmark_title;
bookmark_body= result.body;
bookmark_file_name= result.file_name;
preview_image = result.preview_image;
local_image_name = result.local_image_name;
mainPreviewImage = result.mainPreviewImage;
viewImage=result.viewImage;
var mediaExist =result.mediaExist;
if(mediaExist == 1) {
console.log("Entered in Media Exist");
download(preview_image, "images/" + local_image_name, function() {
console.log("Entered in download");
fs.exists("images/" + local_image_name, function(exists) {
console.log("Before Sending " +mainPreviewImage);
console.log("Before Sending Local " +local_image_name);
ImageMagic(local_image_name,mainPreviewImage,223,147,function(err,result) {
if(result != 0){
mainPreviewImage= result;
console.log("Image Magic Done" +mainPreviewImage);
AmazonUpload(mainPreviewImage,function(err,result) {
console.log("Amazon error "+err);
if(result != 0){
mainPreviewImage = result;
console.log("First Image Uploading is Sucessfully");
/* Now Lets Pass View Image FROM Graphic Magic */
ImageMagic(mainPreviewImage,viewImage,152,100,function(err,result) {
if(result != 0){
viewImage= result;
/* Upload New View File to Amazon */
AmazonUpload(viewImage,function(err,result) {
if(result != 0){
viewImage = result;
console.log("Second Image Upload to Amazon");
/*Finally here we need to write update logic here check it out */
console.log("Serious id is "+i);
console.log("Book Mark id " +bookmark_id);
console.log("bookamrk_title" +bookamrk_title);
console.log("preview_image"+mainPreviewImage);
console.log("viewImage"+viewImage);
console.log("End " +ddd);
}else {
/* need to write update Query here */
var viewImage="thumbnail_default_bookmark1.png";
}
//additional lines to the end of the function
i++;
if (i<bookmarks.length){
bookmark_id = bookmarks[i].id;
bookmark_url = bookmarks[i].url;
parseArticle(i,bookmark_id,bookmark_url,callbackForParseArticle);
} else {
console.log("Every Thing is done ");
}
});
}else{
/* need to write update Query here */
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else {
/* need to writeUpdate Query Here */
var mainPreviewImage= 'default_bookmark.png';
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else{
/* need to write Update Query here */
var mainPreviewImage= 'default_bookmark.png';
var viewImage="thumbnail_default_bookmark1.png";
}
});
});
});/* download function closed */
}
};
if (bookmarks.length > 0){
parseArticle(i,bookmarks[i].id,bookmarks[i].url,callbackForParseArticle);
}
});
}
function AmazonUpload(uploadImage,callback) {
knox.putFile('images/'+uploadImage,'BookmarkPreviewImages/'+uploadImage, {"Content-Type": "image/jpeg",'x-amz-acl': 'public-read'}, function (err, result) {
if(!err){
if(result.statusCode==200){
callback(err,uploadImage);
}else{
callback(err,0);
}
}else{
callback(err,0);
}
});
}
function download(uri, filename, callback) {
request.head(uri, function(err, res, body) {
//request(uri).pipe(fs.createWriteStream(filename),{end:true}).on('close', callback);
var r = request(uri);
r.pause()
r.on('response', function (resp) {
if(resp.statusCode === 200){
r.pipe(fs.createWriteStream(filename),{end:true}).on('close', callback); //pipe to where you want it to go
r.resume()
}
});
});
};
function ImageMagic(local_image_name,display_image,width,height,callback){
console.log("local_image_name is"+local_image_name);
gm('images/'+local_image_name).resize(width, height, '^').gravity('Center').crop(width, height).write('images/'+display_image, function (err) {
if(!err){
console.log("Sucessfully Image converted is "+display_image);
console.log("Sucessfully image which is converted "+ local_image_name);
callback(null,display_image);
}else{
console.log("Graphic Magic Error "+err);
callback(err,0);
}
});
}
function parseArticle(i,bookmark_id,bookmark_url,callback) {
diffbot.article({uri: bookmark_url}, function(err, response) {
var callBackString= {};
console.log("Diffbot Parsing URL with id " +bookmark_id+"and loop id is"+i);
var bookmark_title = response.title;
var body = response.html;
var timestamp = new Date().getTime().toString();
var file_name = common_function.generateRandomString() + timestamp + '.txt';
var timestamp0 = new Date().getTime().toString();
var local_image_name = common_function.generateRandomString() + timestamp0 + i + '.jpg';
var preview_image = response.media[0]['link'];
if(response.media[0].primary=='true'){
mainPreviewImage = "thumb_" + local_image_name;
viewImage = "thumbnail_" + local_image_name;
mediaExist=1;
}else{
mainPreviewImage="default_bookmark.png";
viewImage="thumbnail_default_bookmark1.png";
mediaExist=0;
}
callBackString .bookmark_title=bookmark_title;
callBackString.body = body;
callBackString.file_name = file_name;
callBackString.preview_image = preview_image;
callBackString.local_image_name = local_image_name;
callBackString.mainPreviewImage = mainPreviewImage;
callBackString.viewImage=viewImage;
callBackString.mediaExist =mediaExist;
callback(null,callBackString);
});
};
Use async.js to manage your code flow
If you have multiple functions, func_1, func_2, func_3, that need to run in sequence, the code is
var async = require('async');
var functionList = [func_1, func_2, func_3];
async.series(functionList, function(err, result){
// results of func_1, func_2 and func_3
});

Check empty input and then run script

Is there a way to run a script that check's if #username-input is
empty then run this script:
document.getElementById('login-button').addEventListener('click', function ()
{
var name = document.getElementById('username-input').value;
document.getElementById('username').innerHTML = 'Welcome ' + name;
document.getElementById('username-input').remove();
document.getElementById('password-input').remove();
document.getElementById('login-button').remove();
}, false);
EDIT
And if #username-input and #password-input is empty
an alert is popping up and say that instead of running the script
alert('username or password can't be blank')
it seems that you aren't using JQuery so this would do it.
if (document.getElementById('username-input').value != "") {
document.getElementById('login-button').addEventListener('click', function () {
var name = document.getElementById('username-input').value;
document.getElementById('username').innerHTML = 'Welcome ' + name;
document.getElementById('username-input').remove();
document.getElementById('password-input').remove();
document.getElementById('login-button').remove();
}, false);
}
//define the on success function.
var onSuccess = function () {
document.getElementById('login-button').addEventListener('click', function ()
{
var name = document.getElementById('username-input').value;
document.getElementById('username').innerHTML = 'Welcome ' + name;
document.getElementById('username-input').remove();
document.getElementById('password-input').remove();
document.getElementById('login-button').remove();
}, false);
}
//Get the username and password.
var userName = document.getElementById('username-input').value;
var userName = document.getElementById('password-input').value;
//validate the input
//This if statement will check if either userName or password is null, 0, "", or undefined.
if (userName && password) {
onSuccess();
}
else {
alert("username or password can't be blank");
}
Just use an if statement to check if the div is empty.
if($('#username-input').text() != '') {
document.getElementById('login-button').addEventListener('click', function ()
{
var name = document.getElementById('username-input').value;
document.getElementById('username').innerHTML = 'Welcome ' + name;
document.getElementById('username-input').remove();
document.getElementById('password-input').remove();
document.getElementById('login-button').remove();
}, false);
}
And for the username and password check.
if($('#username-input').text() != '' || $('#password-input').text() != '') {
alert('username or password can't be blank')
}

Categories

Resources