I am getting data from a form and on submit button if data ios not valid it returns false and if data is valid am sending an email through ajax in its success method am showing a modal for sent or not I want window.location.href to be change after modal is hidden as form submits before even modal is displayed so I used event.preventdefault to stop it from submit but now have two issues
browser gets stuch until modal is open
after modal window.location is not being changed.
here is my code for submit button
<input type="submit" class="button btn btn-primary" onclick ="return SendEmail();" />
here is SendEmail()
function SendEmail()
{
if (!CheckContactUsFormValidation()) {
return false;
}
else{
var l_strEmail = document.getElementById('txtEmail').value;
var l_strComents = document.getElementById('txtComments').value;
var l_strEventLocation = document.getElementById('txtEventLocation').value;
var l_strStartDate = document.getElementById('txtStartDate').value;
var l_strOrganization = document.getElementById('txtOrganization').value;
var l_strPhone = document.getElementById('txtPhone').value;
var l_strLastName = document.getElementById('txtLastName').value;
var l_strFirstName = document.getElementById('txtFirstName').value;
var rent = document.getElementById("inlineRadio1").value;
var lease = document.getElementById("inlineRadio2").value;
if (rent.checked == true) {
var l_strCheck = 'rent';
}
else {
if (lease.checked == true) {
var l_strCheck = 'lease';
}
}
var l_strTitle = "Contact Us";
var l_strContents = 'Hi, ' + l_strFirstName + ' ' + l_strLastName + '\n';
l_strContents += 'he is mail for requesting product on ' + l_strCheck + ' and start date is ' + l_strStartDate + ' for organization ' + l_strOrganization + '\n';
l_strContents += 'his cell #' + l_strPhone + ' and his coments are as follows \n';
l_strContents += l_strComents + '\n' + 'You can contact him on email: ' + l_strEmail;
l_strContents += 'End here!';
var l_strtoEmail = 'abc#yahoo.com';
SendEmailWithCustomTitle(l_strtoEmail, l_strContents, l_strTitle);
}
return true;
}
function CheckContactUsFormValidation() {
var m_boolValidator = true;
if (!CheckRequiredFieldValidation('FirstName', 'Enter first name')) {
m_boolValidator = false;
}
if (!CheckRequiredFieldValidation('LastName', 'Enter last name')) {
m_boolValidator = false;
}
if (!CheckRequiredFieldValidation('Organization', 'Enter Organization')) {
m_boolValidator = false;
}
if (!CheckRequiredFieldValidation('Email', 'Enter Email')) {
m_boolValidator = false;
}
else
{
if (!CheckEmailValidation('Email', 'Enter valid email address')) {
m_boolValidator = false;
}
}
if (!CheckRequiredFieldValidation('Phone', 'Enter phone#')) {
m_boolValidator = false;
}
if (!CheckRequiredFieldValidation('StartDate', 'Enter start date')) {
m_boolValidator = false;
}
return m_boolValidator;
}
and here is ajax function being called inside SendEmail()
function SendEmailWithCustomTitle(txtEmail, txtContents, l_strTitle) {
event.preventDefault();
$.ajax({
async:false,
type: "POST",
url: "PTServiceRoutines.aspx/AjaxSendEmail",
data: "{'p_strEmail':'" + txtEmail + "','p_strTitle':'" + l_strTitle + "','p_strContents':'" + txtContents + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successAjaxSendEmailWithCustomTitleHandler,
failure: failureAjaxSendEmailWithCustomTitleHandler,
error: errorAjaxSendEmailWithCustomTitleHandler
});
return false;
}
function successAjaxSendEmailWithCustomTitleHandler(data) {
ShowAlert(data.d);
//ShowAlert is method used to open modal showing data.a
};
function failureAjaxSendEmailWithCustomTitleHandler(data) {
};
function errorAjaxSendEmailWithCustomTitleHandler(data, status) {
};
I have already tried event.preventdefault,event.soppropogation but I could not find any easy way to return true from ajax success function SendEmail call.
Remove async:false, from you ajax to stop the browser from waiting for the ajax to complete
Use the following event to redirect when the modal is closed
$('#myModal').on('hidden.bs.modal', function () {
window.location.href = "desired-page.php"
})
You can create a button in modal and in that button click event, at first hide the modal and the call the ajax call. And window.location.href will not work inside a html form. To make window.location.href work you can move your submit button out of the form.
To open modal in success follow one of following two methods.
.done(function() {
$("#yourmodal").modal();
});
Or
success: function(data) {
$("#yourmodal").modal();
}
To stop ajax call until modal hide use following. Place your ajax call inside a function for an example "submitForm()". call this in following.
$('#yourmodal').on('hidden.bs.modal', function (e) {
// do something...
})
Related
My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
I have been doing some research for this topic and the answers doesn't seem to help me.
I am trying to invoke a method with jquery's ajax callback and it doesn't seem to be working.
Its giving me the following error message
TypeError: this_obj.password_change_request is not a function
Below is the code I am using:
function resetPass() {
// The following code validates the email text field and submit request for password change.
function password_change_request(queryStr) {
$.ajax({
type: "POST", url: "script/password_change_request.php",
data: queryStr
});
}
this.resetPassRequest = function () {
$("#reset_password").click(function () {
var this_obj = this;
var email_address = $("#email_reset").val();
if (email_address == "") {
return false;
} else {
var queryStr = "email=" + email_address + "&store=" + "<?=$store_dir_name?>";
this_obj.password_change_request(queryStr);
return false;
}
});
}
}
The page is jumping to the bottom when the submit button is pushed on the contact form. I think this is caused by js. When you want to try it, push the link below, next contact, fill in the form and press "verstuur"
http://expertlemmer.nl/PC-laptop-reparatie-Lemmer/
javascript:
$('form#contactForm button.submit').on('click', function() {
$('#image-loader').fadeIn();
var contactFname = $('#contactForm #contactFname').val();
var contactLname = $('#contactForm #contactLname').val();
var contactStraat = $('#contactForm #contactStraat').val();
var contactPostcode = $('#contactForm #contactPostcode').val();
var contactTel = $('#contactForm #contactTel').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactFname=' + contactFname + '&contactLname=' + contactLname +
'&contactEmail=' + contactEmail + '&contactSubject=' + contactSubject +
'&contactStraat=' + contactStraat + '&contactPostcode=' + contactPostcode +
'&contactTel=' + contactTel + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
Hello i was on your webpage. And you are using in your script :
$('form#contactForm button.submit').on('click', function() {
e.preventDefault();
// and so on
The problem is that, you do not pass the e in the function. You have to use it like this :
$('form#contactForm button.submit').on('click', function(e) {
e.preventDefault();
// and so on
Then it will prevent the form from refreshing the page. I am just guessing that you want to send the form through ajax.
Your form has no "ACTION" attribute, this means it's posting to the current URL. The current URL has an anchor : #contact, this means you'll jump straight to the contact part.
See what you get when you go into this link and scroll down(Scroll, don't click contact), you'll jump to the review section.
http://expertlemmer.nl/PC-laptop-reparatie-Lemmer/#journal
Long story short, Put an action tag on your form :)
I am trying to craft an AJAX form to display a success/failure/share message via a Fancybox once a user submits their email address on a form. Currently, the code throws the response up to the top of the page.
I have attempted a few variations from other answers provided here here, and here on Stack Overflow, but to no avail, as upon insertion the entire form ceases to load.
My current init.js is as follows:
$("#form").submit(function(e){
e.preventDefault();
leSubmitLoader();
dataString = $("#form").serialize();
var templateURL = $('#templateURL').attr('value');
var blogURL = $('#blogURL').attr('value');
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json",
success:
function(data) {
$.fancybox(
'<p>Content of the box in HTML</p>',
{
padding:15,
closeBtn:true
}
);
function leSubmit(returning){
$.fancybox(
);
$('#form, #error, #presignup-content').hide();
$('#success').fadeIn(function(){
var successScroll = $('#signup-body').offset().top - 20;
$('html,body').animate({scrollTop:successScroll}, 300);
});
if (returning == true) {
$('#returninguser, #returninguserurl').show();
var refCode = data.returncode;
$('#returninguser span.user').text(data.email);
$('#returninguser span.clicks').text(data.clicks);
$('#returninguser span.conversions').text(data.conversions);
$('#returninguserurl input#returningcode').attr('value', blogURL + '/?ref=' + refCode);
} else {
$('#success-content, #newuser').show();
var refCode = data.code;
$('#newuser input#successcode').attr('value', blogURL + '/?ref=' + refCode);
if(data.pass_thru_error == "blocked"){
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html('AWeber Sync Error: Email Blocked.');
} else if (data.pass_thru_error.AWeberAPIException != undefined){
err = data.pass_thru_error.AWeberAPIException;
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html(err.type+': '+err.msg);
}
}
// Referral URL
var refUrl = blogURL + '/?ref=' + refCode;
// Twitter (note: refUrl might not show up in share box on localhost)
var tweetUrl = 'http://twitter.com/intent?url=' + encodeURIComponent(refUrl);
var tweetMessage = $('input#twitterMessage').attr('value');
$('#tweetblock').html('Tweet<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>');
// Facebook (note: won't work on localhost)
$("#fblikeblock").html('<div class="fb-like" data-ref="'+refCode+'" data-href="'+refUrl+'" data-send="false" data-width="75" data-show-faces="false" data-font="arial" data-layout="button_count"></div>');
// Google +
function renderPlusone() {
gapi.plusone.render('plusoneblock', {'href':refUrl, 'size':'tall', 'annotation':'none'});
}
renderPlusone();
// Tumblr
var tumblr_button = document.createElement("a");
tumblr_button.setAttribute("href", "http://www.tumblr.com/share/link?url=" + encodeURIComponent(refUrl) + "&name=" + encodeURIComponent(tumblr_link_name) + "&description=" + encodeURIComponent(tumblr_link_description));
tumblr_button.setAttribute("title", "Share on Tumblr");
tumblr_button.setAttribute("onclick", "window.open(this.href, 'tumblr', 'width=460,height=400'); return false;");
tumblr_button.setAttribute("style", "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('http://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
tumblr_button.innerHTML = "Share on Tumblr";
document.getElementById("tumblrblock").appendChild(tumblr_button);
// RinkedIn
$('#linkinblock').html('<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="'+refUrl+'"></script>');
}
if(data.email_check == "invalid") {
leSubmitLoaderStop();
$('#error').html('This email address is invalid.').fadeIn();
}
else if(data.required.length) {
leSubmitLoaderStop();
$('.error').hide();
$d = String(data.required).split(",");
$.each($d, function(k, v){
$("#" + v + ".error").fadeIn();
});
}
else {
if(data.reuser == "true") {
leSubmit(true);
FB.XFBML.parse(document.getElementById('fblikeblock'));
} else {
leSubmit(false);
FB.XFBML.parse(document.getElementById('fblikeblock'));
}
$('body').addClass('submission-success');
}
}
});
});
I am not trying to fix your code but why you don't use this ajax format to handle success/failure ?
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json"
}).done(function () {
//success
$.fancybox("success", {
// options
});
}).fail(function () {
//error
$.fancybox("failure", {
// options
});
}).always(function () {
// optional after ajax is completed
$.fancybox("else", {
// options
});
});
I have a JavaScript file which has a function that I reference. When I call the function from one part of the code, it works, and from another, it doesn't. Placing the function code above or below the call seems not to make any difference.
The error happens when I call the voteUp function.
Below is the entire JS file. Any idea why the two different calls to that function would have such different results? The call from the code above gives error: undefined function.
$(function()
{
$("#login_div input[type=submit]").click(function()
{
var email = $("#email").val();
var password = $("#user_pass").val();
//alert("Email: " + email);
//alert("password: " + password);
var dataString = 'email='+ email + '&password=' + password;
if( !email )
{
alert ("1");
$('.login_success_email_empty').fadeOut(200).hide();
$('.login_error_email_empty').fadeOut(200).show();
}
else
if( !password || password.length < 5)
{alert ("2");
$('.password_success').fadeOut(200).hide();
$('.password_error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "../auth/login_ajax.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.password_error').fadeOut(200).hide();
$('.no_such_user').fadeOut(200).hide();
$('.login_success_email_empty').fadeOut(200).hide();
$('.login_success').fadeIn(200).show();
// Closing the dialog bosx
$('#loginpopup').dialog('close');
// Swapping out the header div
$('#header_logged_out').hide();
$('#header_logged_in').show();
queue.login = true;
if (queue.voteUp)
{
alert("in vote up queue: " + queue.voteUp + " and login: " + queue.login );
voteUp(queue.voteUp);
}
// Now also need to retrieve the problem_id
//problem_id = $("#problem_id").val();
//$problemId = $('#theProblemId', '#loginpopup').val();
// var $problemId = $('#theProblemId', '#loginpopup');
// alert ("After login, problem_id: " + problem_id + " and problemId was: " + $problemId);
},
error : function(json)
{
queue.login = false;
alert ("error");
// Output the result.
errorMessage = json.responseText;
alert ("ErrorMessage: " + errorMessage );
if ( errorMessage == 'no_such_user' )
{
$('.no_such_user').fadeOut(200).hide();
$('.no_such_user').fadeOut(200).show();
}
}
});
}
return false;
});
});
$(document).ready(function()
{
queue = new Object;
// queue.login = false;
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
var $problemId = $('#theProblemId', '#loginpopup');
$("#newprofile").click(function ()
{
$("#login_div").hide();
$("#newprofileform").show();
});
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{
var problem_id = $(this).attr("data-problem_id");
queue.voteUp = $(this).attr('problem_id');
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id)
{
alert ("In vote up function, problem_id: " + problem_id );
queue.voteUp = problem_id;
var dataString = 'problem_id=' + problem_id + '&vote=+';
alert ("login status: " + queue.login );
if ( queue.login == false )
{
// Call the ajax to try to log in...or the dialog box to log in. requireLogin()
$dialog.dialog('open');
alert ("after dialog was open - in false case of being logged in.");
// prevent the default action, e.g., following a link
return false;
}
else
{
// The person is actually logged in so lets have him vote
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
alert ("vote success, data: " + data);
// Try to update the vote count on the page
//$('p').each(function()
//{
//on each paragraph in the page:
// $(this).find('span').each()
// {
//find each span within the paragraph being iterated over
// }
//}
},
error : function(data)
{
alert ("vote error");
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
queue.login = false;
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
} // End of error case
}); // Closing AJAX call.
} // Closing the else call
};
//$('.vote_down').click(function()
//{
// alert("down");
// problem_id = $(this).attr("data-problem_id");
//
// var dataString = 'problem_id='+ problem_id + '&vote=-';
//Return false to prevent page navigation
// return false;
// });
// $('#loginButton', '#loginpopup').click(function()
// {
/// alert("in login button fnction");
// $.ajax({
// url:'url to do the login',
// success:function()
// {
//now call cote up
// voteUp($problemId.val());
// }
// }); // Closing AJAX call.
//});
}); // End of document.ready() check
The function is declared as a local variable inside your second "ready" handler. Nothing outside that context will be able to call it.
You could make it a global function, maybe, but it depends on whether "queue" is really supposed to be global or not. If it is, it really should be explicitly declared as global (that is, with a var declaration outside the initialization code) because what you've got now is not valid with "strict" mode anyway.