How to Run Onclick Automatically in button - javascript

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

Related

PHP / XMLHttpRequest POST HTML5 Worker Store json echo in variable

I see a lot of these questions comming by. But I seem to do something wrong. So forgive me for asking (I am a bit of a n00b). In my php I echo the the folowing echo json_encode(['msg'=>$NewTotal]);.
I use a HTML5 worker to post data to a php on my server and I need the echo to be posted back to the main script so I can repost it to set it as new value for the variable Totalaccounts for the loop.
Worker Script:
onmessage = function(dbs) {
console.log(dbs.data);
var Totalaccounts = dbs.data;
var DBScriptLoop = setInterval(
(function () {
DBStartWorking();
//postMessage(Totalaccounts);
}), 123000);
function DBStartWorking(){
for (var dw = 0; dw < Totalaccounts; dw++) {
setTimeout(function() {
httpRequest = new XMLHttpRequest()
var dataresponse = httpRequest.responseText;
var NewCount = dataresponse.msg;
httpRequest.open('POST', 'DostuffV1.php')
httpRequest.send(Totalaccounts)
postMessage(NewCount);
console.log(NewCount);
}, 1200 * dw);
}
} // End script loop
};
Main script:
var DBScriptWorker;
function startDBScriptWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(DBScriptWorker) == "undefined") {
DBScriptWorker = new Worker('DBScriptWorker.js');
var php_va = "<?php echo $AccToRank; ?>";
DBScriptWorker.postMessage(php_va);
}
DBScriptWorker.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
DBScriptWorker.postMessage(event.data);
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
}
}
function stopDBScriptWorker() {
DBScriptWorker.terminate();
DBScriptWorker = undefined;
}
In my network tab I see the response is this: {"msg":29}
My variable is not set, it commes up as undifined. What am I doing wrong? Searching and trying for hours now..

Javascript - confirmation dialog after form submission

I am not a Javascript wiz so need some help with the following. I have a popup asking people to type in their email address. Right now the popup just closes after submission, which isn't a nice user experience. Ideally the text bar and the submission button would disappear, and be replaced by a short comment such as "Thanks, we'll be in touch". Even better would be if the popup would then disappear after "N" seconds.
Can anyone help?
var self = this;
var showDelay = parseInt('[[ bannerShowDelayInMilliseconds ]]' || '0', 10);
setTimeout(function () {
requestAnimationFrame(function () {
if (!self.inPreview && "true" == "{{ 'true' if customer.email else 'false' }}") {
return;
}
self.sdk.track('banner', getEventProperties('show', false));
document.body.insertAdjacentHTML('beforeend', self.html);
var banner = self.banner = document.querySelector('.exponea-subscription-dialog');
self.backdrop = document.querySelector('.exponea-subscription-dialog + .exponea-banner-backdrop');
banner.insertAdjacentHTML('afterbegin', '<style>' + self.style + '</style>');
var form = banner.querySelector('form');
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("dialogue").innerHTML = "Thank you message";
setTimeout(function(){ removeBanner(); }, 3000);
}
return false;
};
var btnClose = banner.querySelector('.exponea-close');
btnClose.onclick = function () {
removeBanner();
self.sdk.track('banner', getEventProperties('close'));
};
});
}, showDelay);
function getEventProperties(action, interactive) {
return {
action: action,
banner_id: self.data.banner_id,
banner_name: self.data.banner_name,
banner_type: self.data.banner_type,
variant_id: self.data.variant_id,
variant_name: self.data.variant_name,
interaction: interactive !== false ? true : false,
location: window.location.href,
path: window.location.pathname
};
}
function removeBanner() {
if (self.banner) {
self.banner.parentNode.removeChild(self.banner);
}
if (self.backdrop) {
self.backdrop.parentNode.removeChild(self.backdrop);
}
}
function validateEmail(email) {
return email && /^\S+#\S+\.\S+$/.test(email);
}
return {
remove: removeBanner
};
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("thankYouIdExample").innerHTML = "Thank you message";
setTimeout(function(){ removeBanner(); }, 3000);
}
return false;
Just make sure to place the <div id="thankYouIdExample"></div> at the right place.
Let me know if it works for you m8
You can insert your thanks message in another container, and write something like this:
<div id="container">
<div id="form">
here is the form and everything that belongs here
</div>
<div id="thanks">
here is the thanks message
</div>
</div>
With this, you can set the default style of the thanks div to display: none; in css.
If you reference the container divs in js by their ids, you can change their style from js. The setTimeout() method can be used to time the closing of the dialog box, assuming it is done by the removeBanner() function. You can add these lines:
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("form").style.display = 'none';
document.getElementById("thanks").style.display = 'block';
setTimeout(function(){removeBanner();}, 5000);
}
return false;
This way you can have a fully pre-customized thanks message.
Use setTimeout
https://www.w3schools.com/jsref/met_win_settimeout.asp
https://developer.mozilla.org/de/docs/Web/API/WindowTimers/setTimeout
form.onsubmit = function() {
var eventProperties = getEventProperties('subscribe')
var email = (form.email.value || '').toLowerCase()
eventProperties.subscription_email = email
self.sdk.track('banner', eventProperties)
if(validateEmail(email)) {
self.sdk.update({
email: email
})
setTimeout(() => {
alert("Thatnk You") // you may want to replace it with a own dialogue system
removeBanner()
}, 5000) // wait 5000 milliseconds or in other words 5 seconds
}
return false
}
Asynchronous version (if you want to return after the 5000 wait):
*only useful if you not directly call the handler
form.onsubmit = async function() {
return Promise((resolve, reject) => {
var eventProperties = getEventProperties('subscribe')
var email = (form.email.value || '').toLowerCase()
eventProperties.subscription_email = email
self.sdk.track('banner', eventProperties)
if(validateEmail(email)) {
self.sdk.update({
email: email
})
setTimeout(() => {
alert("Thatnk You") // you may want to replace it with a own dialogue system
removeBanner()
resolve()
}, 5000) // wait 5000 milliseconds or in other words 5 seconds
}
else reject()
})
}

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

Javascript callback function executed 2 times

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)

Changing url using javascript and jquery

Hello there
I am developing a jQuery plugin that loads files through ajax. When user clicks on a button which is:
<button class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
When user clicks on button it generates following url:
http://localhost//plugins/ajaxLoad/index.html#ajax/Login
I want to change it to
http://localhost//plugins/ajaxLoad/index.html/ajax/Login
My javascript is:
(function ($) {
$.fn.ajaxLoad = function (options) {
var settings = $.extend({
fileUrl : 'null',
loadOn : '.em'
}, options);
$('[data-load="ajax"]').each(function(index, el) {
$(this).click(function () {
var file = $(this).attr('data-file');
var loadOn = $(this).attr('data-load-on');
var permission = $(this).attr("data-ask-permission");
settings.fileUrl = file;
settings.loadOn = loadOn;
if (permission == 'yes') {
var ask = confirm("Do you want to load file");
if (ask == true) {
$.fn.loadFile();
}
}else {
$.fn.loadFile();
}
});
});
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.split(".");
location.hash = a[0];
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}
}(jQuery))
Can anyone tell me how to change url in jquery and Javascript.
You need to use history.pushstate() to do this.
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Have a look at this article on MDN for more details
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
This article gives some nice jQuery examples.
https://rosspenman.com/pushstate-jquery
Added another attribute title to button
<button data-title="login" class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
In Js (after $(this).click line):
var title = $(this).attr('data-title');
settings.title = title
Just replace
location.hash = a[0];
With
history.pushState('','',"?"+settings.title);
Change
location.hash = a[0];
to:
location.pathname += '/' + a[0];
Just replace the hash with a blank using .replace()
Example .
settings.fileUrl.replace('.' , ' ');
Updated above also
UPDATE :
Don't hash the URL
Example :
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.replace("." , "/");
location.href = a;
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}

Categories