my ajax post request is called twice - javascript

I have some javascript code in my wordpress site that post an ajax request to a php file and then the file generates a pdf with a quote.
It all works, but I don't understand why the second time I submit the request (to create the second quote, basically), the ajax request then is called twice?
the first time is correct, and it's called one time.
from the second time, it's always called twice.
here's the code:
$('#add-to-cart-quote-email-button').on('click', function() {
var statusIcon;
statusIcon = $('#quote-send-spinner');
$('.send-quote-from-cart-page-container').slideToggle();
statusIcon.removeClass('fa fa-check');
statusIcon.removeClass('fa fa-times');
$('#cart-quote-email-send-button').on('click', function(e) {
var data, email, name, quote_type, role;
e.preventDefault();
name = $('.send-quote-from-cart-page-container #name');
email = $('.send-quote-from-cart-page-container #email-address');
role = $('.send-quote-from-cart-page-container #user-role').val();
quote_type = $('.send-quote-from-cart-page-container #quote-type').val();
if (!name.val()) {
console.log("empty name");
name.addClass('invalid');
return;
} else {
if (name.hasClass('invalid')) {
name.removeClass('invalid');
}
}
if (!validateEmail(email.val())) {
console.log("invalid email");
email.addClass('invalid');
return;
} else {
if (email.hasClass('invalid')) {
email.removeClass('invalid');
}
}
console.log("sent! to email " + (email.val()) + " and name " + (name.val()));
data = {
name: name.val(),
email: email.val(),
role: role,
quote_type: quote_type
};
statusIcon.addClass('fa fa-spinner fa-spin fa-fw');
$.ajax({
type: 'post',
dataType: 'json',
url: '/wp-admin/admin-ajax.php',
data: 'cxecrt-success-get-link-url=&cxecrt-saved-cart-name=&cxecrt-landing-page=cart&action=save_cart_and_get_link_ajax',
success: function(response) {
data.cartURL = response.cart_url;
return $.ajax({
method: 'POST',
url: '/wp-content/themes/theme/generate_pdf_quotes/emailQuote.php',
data: data,
success: function() {
console.log("success!");
statusIcon.removeClass('fa fa-spinner fa-spin fa-fw');
statusIcon.addClass('fa fa-check');
return setTimeout(function() {
return $('.send-quote-from-cart-page-container').slideToggle();
}, 2000);
},
fail: function() {
console.log("fail");
statusIcon.removeClass('fa fa-spinner fa-spin fa-fw');
return statusIcon.addClass('fa fa-times');
}
});
}
});
});
});
return;
I need to call the second ajax on success of the first one, as they do two completely different things and the first one is required by the second one, that it's meant to be like that and it's not (i believe) the cause of this issue
I inspected the code but I couldn't see anything wrong in here.
Any thoughts?
thanks

You are defining an eventHandler within the first eventHandler.
On line 1:
$('#add-to-cart-quote-email-button').on('click', function() {
On line 7:
$('#cart-quote-email-send-button').on('click', function(e) {
That's why the second time it is clicked, it calls twice. I bet if you click it a third time it calls 3x ;-)

Related

div.load() causing full page postback

After saving form data, need to load the div only not whole page refresh but it first goes to Main Page Action Controller and then the DIV Load Partial Action Controller. I am unable to find the reason why it is posting whole page.
I have added the preventDefault() command too.
$("#btnSave").click(function (e) {
e.preventDefault();
var url = "#Url.Action("Save", "Note")";
var id = "1";
var model = {
modelfields.....
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
success: function (data) {
if (data == "True") {
// Load div
var settings = { editUrl: '#Url.Action("Get", "Note", new { ID = "-1" })' };
settings.editUrl = settings.editUrl.replace("-1", id);
$("#divNoteDetails").load(settings.editUrl);
}
else if (data == "False") {
alert('not saved');
}
},
error: function () {
alert('error');
}
});
return false;
});
if your button is inside a form then its default type is submit. see the spec for details
try adding type="button" to the button, or event.preventDefault() on an event handler attached to the form itself.

ajax loading indicator stopped in between

I am saving data on a save button click that calls ajax and passing json data to a controller method but when we save it loading starts and suddenly stop though the data is not saved.
It is not working I have tried it in all way but not working please help me on this.
<button type="button" id="saveDeleg" class="btn_reg_back btnmainsize btnautowidth btngrad btnrds btnbdr btnsavesize " aria-hidden="true" data-icon="">#Resources.Resource.Save</button>
$('#saveDeleg').click(function() {
var response = Validation();
if (!response) {
return false;
}
$("#overlay").show();
$('.loading').show();
if ($('#organName').val() == '') {
$('#validorganisation').show();
return false;
} else {
$('#validorganisation').hide();
}
//Contact name
var SubDelegation = $('#subdelegation').is(':checked');
var CopyNotification = $('#copynotification').is(':checked');
var ArrangementId = $("#ArrangementId").val();
var paramList = {
ArrangementId: ArrangementId,
ArrangementName: $('#arrangName').val(),
OrganisationName: $('#organName').val(),
OrganisationId: $('#OrganisationId').val(),
ContactName: $('#contactName').val(),
ContactId: $('#ContactId').val(),
SubDelegation: $('#subdelegation').is(':checked'),
CopyNotification: $('#copynotification').is(':checked'),
ContactType: $('#ContactType').val(),
SelectedTypeName: $("input[name$=SelectedType]:checked").val()
};
setTimeout(function() {
$.ajax({
async: false,
type: "POST",
url: '#Url.Action("SaveDelegation", "Structures")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paramList),
processdata: true,
success: function(result) {
//stopAnimation()
paramList = null;
if (result == 0) {
window.location.href = '../Structures/MyDelegationArrangement';
} else if (result == 1) {
window.location.href = '../Structures/CreateDelegation';
} else if (result == 2) {
window.location.href = '../Home/Error';
} else if (result == 3) {
window.location.href = '../Account/Login';
} else {
//validation message
alert('Error');
}
},
error: function() {},
complete: function() {
$("#overlay").hide();
$('.loading').hide();
}
});
}, 500);
});
The problem with the loading indicator is because you used async: false which locks up the UI. Remove that setting.
Also note that if the data is not being saved I would assume that your AJAX call is returning an error. If so, check the console to see the response code. It may also be worth putting some logic in the error callback function to give you some information on whats happened, as well as inform your users about what to do next.

Why webkit notification event does not trigger?

I have wrote a webkit notification script on my web app to pull notifications from a database. The code is seen below:
function checkNotifications() {
if (window.webkitNotifications.checkPermission() == 1) {
window.webkitNotifications.requestPermission();
}
else {
$.ajax({
type: "GET",
dataType: 'json',
url: '/check_notifications',
success: function(data){
if (data){
var ticketId = data.ticket_id;
console.log(data);
var comment = data.comment;
var createdDate = data.created_at;
var notificationComment = data.comment;
var notificationId = data.notifcation_id;
var notification = window.webkitNotifications.createNotification('/pt_logo_small.png', 'Project Ticket '+ticketId+ ' Updated!', 'Ticket has been updated. Click here to see!');
notification.show();
console.log(notificationId);
notification.onclick = function(){
this.close();
console.log("NOTIFICATION WAS CLICKED!")
$.ajax({
type: "GET",
dataType: 'json',
url: '/read_notifications/' + notificationId,
success: function(){
window.location = '/pto/' + ticketId;
},
error: function(){
window.location = '/pto/' + ticketId;
}
});
console.log(ticketId, comment, createdDate);
};
}
}
});
}
setTimeout(checkNotifications, 20000);
}
For some reason. I if select another tab, or go to another path inside my webapp, the script still runs to display the notifications, however the .onclick event never triggers.
Anyone have any idea why the even wouldn't trigger?
According to Apple, onclick should bring the page which created the event to focus, which it does. However nothing inside my .onclick function triggers.

Ajax success function firing before java class responds

I am creating a login function with ajax and am having an issue where the success function (SuccessLogin) fires before getting an ajax response. I am running the code as google web app from eclipse and I can see when debugging the java class file, that the javascript is throwing an alert for the success response from the class being false before the debugger catches the break point in the class file. I have only been writing code for a couple months now so I am sure its a stupid little error on my part.
$(document).ready(function() {
sessionChecker()
// sign in
$('#signInForm').click(function () {
$().button('loading')
var email = $('#user_username').val();
sessionStorage.email = $('#user_username').val();
var password= $('#user_password').val();
var SignInRequest = {
type: "UserLoginRequest",
email: email,
password: password
}
var data= JSON.stringify(SignInRequest);
//disabled all the text fields
$('.text').attr('disabled','true');
//start the ajax
$.ajax({
url: "/resources/user/login",
type: "POST",
data: data,
cache: false,
success: successLogin(data)
});
});
//if submit button is clicked
$('#Register').click(function () {
$().button('loading')
var email = $('#email').val();
if ($('#InputPassword').val()== $('#ConfirmPassword').val()) {
var password= $('input[id=InputPassword]').val();
} else {alert("Passwords do not match");
return ;}
var UserRegistrationRequest = {
type: "UserRegistrationRequest",
email: email,
password: password
}
var data= JSON.stringify(UserRegistrationRequest);
//disabled all the text fields
$('.text').attr('disabled','true');
//start the ajax
$.ajax({
url: "/resources/user/register",
type: "POST",
data: data,
cache: false,
success: function (data) {
if (data.success==true) {
//hide the form
$('form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
} else alert('data.errorReason');
}
});
return false;
});
});
function successLogin (data){
if (data.success) {
sessionStorage.userID= data.userID
var userID = data.userID
sessionChecker(userID);
} else alert(data.errorReason);
}
//session check
function sessionChecker(uid) {
if (sessionStorage.userID!= null){
var userID = sessionStorage.userID
};
if (userID != null){
$('#user').append(userID)
$('#fat-menu_1').fadeOut('slow')
$('#fat-menu_2').append(sessionStorage.email).fadeIn('slow') };
}
success: successLogin(data)
There's a difference between a function call and a function definition:
A function definion uses the function keyword and contains a function body {...}
A function call appends parentheses (argument list) to the function name and actually calls the function to return a value
If you assign a function call to the property, it will return a value and that will be what is stored. To avoid this, if your function does not take any parameters you can use the function name, or if your function does take a parameter, embed your function call in another function's definition:
No parameter: success: successLogin
Has parameter: success: function() { successLogin(data); }
You need to wrap your success in an anonymous function in order for it to execute within the scope of the AJAX call instead of being executed inline (immediately):
success: function() { successLogin(data) }

Updating jQuery Item during Ajax call

I am making an ajax call to send out a couple of emails when the user clicks a button. I am trying to update a "Please wait..." div before and after the call with the status, as well as report any errors. The problem... is that the div doesn't actually update until the ajax call is complete.
If I comment out the ajax call the status update works fine, but fails if the ajax call takes place. My Windows programming experience tells me the div needs to be refreshed, but I'm not sure how this is done, or if this is the right method.
For example:
$("#msgEmail").show();
$("#msgEmail").html("Preparing to send");
$.ajax({ blah blah blah...
Any pointers in the right direction will be much appreciated!
On nnnnnn's suggestion I started testing on other browsers. The problem occurs on Chrome and Safari, but works as expected on Firefox and SeaMonkey. It sure looks like he's right about this. Now I just need to figure out to implement setTimeout() in this scenario.
Update: Code:
.click(function() {
$('#myTable :checkbox:checked').each(function() {
sId = $(this).attr('cid');
sName = $(this).attr('cname');
ret = true;
$("#msgImage").slideDown();
sUpdate = 'Sending alerts to class: '+ sName;
$("#msgEmail").slideDown();
$("#msgEmail").html(sUpdate);
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData= "cid="+sId+'&sname='+sName+'&subject='+sSubject+'&message='+encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function (msg)
{
if(msg >= '1')
{
ret = true;
}
}
});
if(ret)
$("#msgEmail").html('Finished sending alerts');
$("#msgImage").slideUp();
ret = false;
return false;
})
Place your ajax call in the callback for 'slideDown'. Set the message before calling 'slideDown'. This will ensure your message is updated before the ajax call is sent.'
sUpdate = 'Sending alerts to class: ' + sName;
$("#msgEmail").html(sUpdate);
$("#msgEmail").slideDown(function() {
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData = "cid=" + sId + '&sname=' + sName + '&subject=' + sSubject + '&message=' + encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function(msg) {
if (msg >= '1') {
ret = true;
}
}
});
});
I ll get you an on hw this stuff is going to be
$(document).ready(function(){
$.ajax({
url :'YOur url',
.....
.....
ajaxSend :function(){
$('#yourdiv').html('please wait...');
}
success:function(msg){
if (msg >= '1') {
$('#yourdiv').html('validated');
}
}
});
}):

Categories

Resources