Javascript callback function executed 2 times - javascript

users can sign in to my system using google sign in so when use pressing google sign in button his account will be create in mysql database
my problem is every users account created two time when user trying to sign in by google
in other words function of create account executed two time for every user
here is my html code
<a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a>
this is javascript code
function gPOnLoad(){
// G+ api loaded
document.getElementById('gp_login').style.display = 'block';
}
function googleAuth() {
gapi.auth.signIn({
callback: 'gPSignInCallback',
clientid: '636950137786-j3siaftgshtf9iamovisf603pplv7jf1.apps.googleusercontent.com',
cookiepolicy: "single_host_origin",
requestvisibleactions: "http://schema.org/AddAction",
scope: "https://www.googleapis.com/auth/plus.login email https://www.googleapis.com/auth/user.phonenumbers.read https://www.googleapis.com/auth/user.birthday.read"
})
}
function gPSignInCallback(e) {
if (e["status"]["signed_in"]) {
gapi.client.load("plus", "v1", function() {
if (e["access_token"]) {
getProfile()
} else if (e["error"]) {alert(e['error'])
console.log("There was an error: " + e["error"])
}
})
} else {alert(e["error"]);
console.log("Sign-in state: " + e["error"])
}
}
function getProfile() {
//var e = googleData.getBasicProfile();
var e = gapi.client.plus.people.get({
userId: "me"
});
e.execute(function(e) {
if (e.error) {alert(e.message)
console.log(e.message);
return
} else if (e.id) {var msgs=JSON.stringify(e);
alert(e.displayName);
update_user_data(e);
// save profile data
}
})
}(function() {
var e = document.createElement("script");
e.type = "text/javascript";
e.async = true;
e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
var t = document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e, t)
})()
function update_user_data(response)
{
// var dataString = JSON.stringify(response);
var email=response.emails[0]['value'];
var displayName=response.displayName;
//ar
$.ajax({
type: "POST",
data: {email:email,displayName:displayName},
url: 'Save.php?id=check_user',
success: function(msg) {
var array = msg.split(',');
var email =array[0];alert(email);
var password = array[1];alert(password);
$('#username').val(email);$('#password').val(password);
document.getElementById("modal4c").click();
},
error: function(XMLHttpRequest,textStatus,errorThrown) {//alert(JSON.stringify(msg));
}
});
}
update_user_data() function is to insert account into mysql database but this function is called twice per user.

Not sure why you function runs twice but,
one way to ensure a function runs only once would be make some global flag like this
runOnce = false;
function gPSignInCallback(e) {
if(runOnce) return;
runOnce = true;
// ... rest of the function
}
If you want to avoid global vars you could return a closure like this
function update_user_data(e){
var runOnce = false
return function(){
if(runOnce) return;
runOnce = true;
// ... rest of the function
}
}
And call it like this update_user_data()(e)

Related

How can I redirect to an action in .Net Core after making an Ajax call?

I have a script that makes an ajax call to an action in the controller and save some records.
The whole process is working fine but my little issue is to redirect to another page after saving records successfully.
With my code below, the records were added successfully with an alert indicating as it is described in the code "msg + "Courses were Registered"". Rather than doing that I want it to redirect to an action.
Javascript code:
<input type="submit" value="Register Courses" id="register" class="btn btn-rose" />
<script>
$(document).ready(function () {
$("#register").click(function () {
var items = [];
$('input:checkbox.checkBox').each(function () {
if ($(this).prop('checked')) {
var item = {};
item.CourseID = $(this).val();
item.CourseCode = $(this).parent().next().html();
item.CourseName = $(this).parent().next().next().html();
item.Units = $(this).parent().next().next().next().html();
items.push(item);
}
});
var options = {};
options.url = "/Course/SaveCourse";
options.type = "POST";
options.dataType = "json";
options.data = JSON.stringify(items);
options.contentType = "application/json; charset=utf-8;";
options.success = function (msg) {
alert(msg + " Courses were Registered");
};
options.error = function () {
alert("Error while Registering Courses");
};
$.ajax(options);
});
});
</script>
Controller
[HttpPost]
public IActionResult SaveCourse([FromBody]List<CourseRegModel> courseIDs)
{
var user = HttpContext.Session.GetString("currentUser");
if (user == null)
{
return RedirectToAction("Login", "Account");
}
ViewBag.student = user;
var pendingPayment = (from row in _context.BursaryTransactions where row.MatricNo == user && row.ResponseCode == "021" select row).Count();
if (pendingPayment > 0)
{
return RedirectToAction("PaymentSummary", "Student");
}
var student = _context.StStudentInfo.Include(m =>m.AdmInstProgramme.AdmInstDepartment).Include(m =>m.AdmInstClassLevels).FirstOrDefault(m => m.MatricNo == user);
var session = _context.AdmInstProgrammeTypeSession.Include(m => m.AdmInstSemesters).Include(m => m.AdmInstSessions).Include(m => m.AdmInstProgramType).Where(m => m.IsActive == true).FirstOrDefault(m => m.ProgramTypeId == student.ProgrammeTypeId);
foreach (CourseRegModel courseID in courseIDs)
{
courseID.Level = student.AdmInstClassLevels.ClassLevel;
courseID.Semester = session.AdmInstSemesters.Semester;
courseID.Session = session.AdmInstSessions.SessionName;
courseID.Department = student.AdmInstProgramme.AdmInstDepartment.Department;
_context.CourseRegModel.Add(courseID);
}
int courses = _context.SaveChanges();
return Json(courses);
}
Objective is to return RedirectToAction("MyCourses","Courses"); after SaveChanges();
If you want to redirect to another action method why would you use AJAX? But I think you can work around that by performing the redirect in the client side AJAX after it is successfully receive a response you use JavaScript to do the redirect
You can simply redirect your page inside ajax's success handler,
options.success = function (msg) {
window.localtion.href = "/Courses/MyCourses";
// or window.location.href = '#url.Action("MyCourses","Courses")';
};

Session TImeout after logon?

Below is a logon code I have set up with html. I would like to set a timeout setting to initiate a log off function after x minutes idle time. Is this possible? I currently have a log off button that initiates the log off, so possibly have that timeout select that function. Thank you.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>Enter credentials</legend>
<p>
<label for="username">User name:</label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
</p>
</fieldset>
<input type="submit" id="login-button" name="login-button" value="Log On" />
</form>
<script src="scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Web Proxy request to fetch the configuration
ajaxWrapper({ url: 'Home/Configuration', dataType: 'xml', success: configSuccess });
$('form').submit(function () {
var username = $('#username').val(),
password = $('#password').val();
clearMessage();
if (!username || !password) {
showMessage('Enter a username and a password');
return false;
}
// Ensure the user name is correct...
// If the username has the domain string at position 0, then
// the username is correct and just use it as normal, but if
// not, username needs to have the domain prepended.
// Because of the backslashes in the strings, they need to be
// escaped with "\\"
username = username.indexOf("domain\\") === 0 ? username : "domain\\" + username;
// Web Proxy request to log the user on
ajaxWrapper({
url: 'PostCredentialsAuth/Login',
dataType: 'xml',
success: loginSuccess,
error: loginError,
data: { username: username, password: password }
});
return false;
});
});
</script>
Below is the code I added to the section after the logonsuccess form is selected.
function loginSuccess(data) {
var $loginXml = $(data),
result = $loginXml.find('Result').text();
if (result == 'success') {
$('form').hide();
$('#log-off').show();
// Set timeout variables.
var timoutWarning = 60000; // Display warning in 14 Mins.
var timoutNow = 30000; // Warning has been shown, give the user 1 minute to interact
var logoutUrl = '($configXml.find('authManager').attr('logoffURL'));'; // URL to logout page.
var warningTimer;
var timeoutTimer;
// Start warning timer.
function StartWarningTimer() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
}
// Reset timers.
function ResetTimeOutTimer() {
clearTimeout(timeoutTimer);
StartWarningTimer();
$("#timeout").dialog('close');
}
// Show idle timeout warning dialog.
function IdleWarning() {
clearTimeout(warningTimer);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
$("#timeout").dialog({
modal: true
});
// Add code in the #timeout element to call ResetTimeOutTimer() if
// the "Stay Logged In" button is clicked
}
// Logout the user.
function IdleTimeout() {
window.location = logoutUrl;
}
And below is the Log Off button that is shown where a user can manually log off.
$('#log-off').click(function () {
// Web Proxy request to log the user off
url = ($configXml.find('authManager').attr('logoffURL'));
ajaxWrapper({ url: url, dataType: 'text', success: logoffSuccess });
return false;
});
});
Your code doesn't call incativityTime function. Call the function on window onload (or jquery onready) like window.onload = function() { inactivityTime() };
<html>
<body>
<script>
window.onload = function() { inactivityTime() };
var inactivityTime = function ()
{
var t;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 3000)
// 1000 milisec = 1 sec
}
}
</script>
</body>
</html>
I added it with no success. Below is how the logon success code looks.
function loginSuccess(data) {
var $loginXml = $(data),
result = $loginXml.find('Result').text();
if (result == 'success') {
$('form').hide();
$('#log-off').show();
// Web Proxy request to enumerate the resources available to the user
url = $configXml.find('resourcesProxy').attr('listURL');
ajaxWrapper({ url: url, success: listResourcesSuccess });
} else {
showMessage('Login failed - try again');
}
var inactivityTime = function () {
var t;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 3000)
// 1000 milisec = 1 sec
}
};
}

How to Run Onclick Automatically in button

I'm trying to automatically run the onclick function in one button placed in phtml template.
This is the html file with the button code:
<button type="button" id="review-btn" title="<?php echo $this->__('Place Order') ?>" class="button btn-checkout" onclick="review.save();"><span><span><?php echo $this->__('Place Orderxxxxx') ?></span></span></button>
This is part of javascript file with save and review functions:
//review function starts
var Review = Class.create();
Review.prototype = {
initialize: function(form,saveUrl,successUrl,agreementsForm){
this.form = form;
this.saveUrl = saveUrl;
this.successUrl = successUrl;
this.agreementsForm = agreementsForm;
this.onSave = this.nextStep.bindAsEventListener(this);
this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
},
//function triggers when onloading on review save function
loadingbox: function () {
var translate = Translator.translate('processing').stripTags();
$("review-please").update(' <div class="please-wait-loading"> </div><span class="load-wait">'+translate+'</span>')
var form = $('review-btn');
form.disabled='true';
},
save: function(){
var paymentmethod = payment.currentMethod;
var validator = new Validation(this.form);
if (validator.validate()) {
var request = new Ajax.Request(
this.saveUrl,
{
method:'post',
parameters: Form.serialize(this.form),
onLoading:this.loadingbox.bind(this),
onComplete: this.onComplete,
onSuccess: function(transport) {
if(transport.status == 200) {
var data = transport.responseText.evalJSON();
if(!data.success)
{
alert(data.error_messages);
$("review-please").update('');
$('review-btn').disabled='';
}
if (data.redirect) {
location.href = data.redirect;
return;
}
if(data.success){
//hostedpro and advanced payment action
if(paymentmethod == 'hosted_pro' || paymentmethod =='payflow_advanced')
{
Element.hide('review-please');
Element.hide('review-btn');
document.getElementById('checkout-paypaliframe-load').style.display= 'block';
iframedata = data.update_section["html"].replace("display:none","display:block");
document.getElementById('checkout-paypaliframe-load').innerHTML = iframedata;
}
else //other payment action
{
this.isSuccess = true;
window.location = data.success;
}
}
}
},
onFailure: checkout.ajaxFailure.bind(checkout)
}
);
//var updater = new Ajax.Updater('product-details', this.saveUrl, {method: 'post',parameters: Form.serialize(this.form)});
}
},
If I simply change the onclick to setTimeout it doesn't work.
Use setTimeout in your javascript file.
Second parameter is time in milliseconds (1000ms = 1s), after which function will be executed.
setTimeout(review.save, 1000);
EDIT:
Sinde you use this in your function, you need to overwrite this. If called independently, scope isn't same anymore.
setTimeout(function(){
review.save.apply(document.getElementById('review-btn'));
}, 1000);
Full code
Add this to last row of your JS file.
window.onload = function(){
setTimeout(function(){
review.save.apply(document.getElementById('review-btn'));
}, 1000);
};

Proper syntax for javascript callback

I have a syntax error on the code below, all I want is a function to be executed on a call back but I am not sure what the error is.
should be close to:
onClickCallback: UpdateBillCycleStatusToCompleted(1)
<script type="text/javascript">
SP.SOD.executeFunc("callout.js", "Callout", function () {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.BaseViewID = 'Callout';
// Define the list template type
itemCtx.ListTemplateType = 101;
itemCtx.Templates.Footer = function (itemCtx) {
// context, custom action function, show the ECB menu (boolean)
return CalloutRenderFooterTemplate(itemCtx, AddCustomCompleteAction, true);
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
});
function AddCustomCompleteAction(renderCtx, calloutActionMenu) {
// Add your custom action
calloutActionMenu.addAction(new CalloutAction({
text: "Custom Action",
tooltip: 'This is your custom action',
onClickCallback: UpdateBillCycleStatusToCompleted(1)
}
}));
// Show the default document library actions
CalloutOnPostRenderTemplate(renderCtx, calloutActionMenu);
// Show the follow action
calloutActionMenu.addAction(new CalloutAction({
text: Strings.STS.L_CalloutFollowAction,
tooltip: Strings.STS.L_CalloutFollowAction_Tooltip,
onClickCallback: function (calloutActionClickEvent, calloutAction) {
var callout = GetCalloutFromRenderCtx(renderCtx);
if (!(typeof (callout) === 'undefined' || callout === null)) callout.close();
SP.SOD.executeFunc('followingcommon.js', 'FollowSelectedDocument', function () {
FollowSelectedDocument(renderCtx);
});
}
}));
}
function UpdateBillCycleStatusToCompleted(itemId) {
alert('Completed');
//var clientContext = new SP.ClientContext.get_current();
//var oList = clientContext.get_web().get_lists().getByTitle('Bill Cycles');
//this.oListItem = oList.getItemById(itemId);
//oListItem.set_item('Bill Cycle Preparation Status', 'Completed');
//oListItem.update();
//clientContext.executeQueryAsync(Function.createDelegate(this, this.StatusCompletedSucceeded), Function.createDelegate(this, this.StatusCompletedFailed));
}
function StatusCompletedSucceeded() {
alert('Item updated!');
}
function StatusCompletedFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
Unless UpdateBillCycleStatusToCompleted(1) actually return function() {...} then you're doing it wrong.
onClickCallback: function() {UpdateBillCycleStatusToCompleted(1);}
That sort of thing should work.

"The page you requested is invalid" when trying to sign into Google ..for import Gmail Contacts

I add the external script in head
http://www.google.com/jsapi
Body Part:
google.load("gdata", "1.s");
google.setOnLoadCallback(function (){
if(window.location.hash=="") {
if(!checkLogin()){
logMeIn();
} else {
var feedUrl = "https://www.google.com/m8/feeds/contacts/default/full";
query = new google.gdata.contacts.ContactQuery(feedUrl);
query.setMaxResults(5000);
myService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
myService.getContactFeed(query, function(result) {
document.cookie="g314-scope-0=";
window.opener.parseGmailContacts(result.feed.entry);
close();
}, function(e){
alert(e.cause ? e.cause.statusText : e.message);
});
}
}
});
function logMeIn() {
scope = "https://www.google.com/m8/feeds";
var token = google.accounts.user.login(scope);
}
function logMeOut() {
google.accounts.user.logout();
}
function checkLogin(){
scope = "https://www.google.com/m8/feeds/";
var token = google.accounts.user.checkLogin(scope);
return token;
}
after page open it goes to https://accounts.google.com/AuthSubRequestJS?session=1&scope=https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds&next=http%3A%2F%2Fmaharashtratimes.indiatimes.com%2Fsocial_gmail.cms
and it;shown The page you requested is invalid. Please help.................

Categories