Javascript not waiting for ajax with bootstrap-wizard.js - javascript

I have a bootstrap-wizard as follows:
<div class="wizard-card" data-cardname="credential">
<h3>Credential</h3>
<div class="wizard-input-section">
<p>Username</p>
<div class="form-group">
<div class="col-sm-6">
<input type="text" class="form-control" id="Busername" name="Busername" placeholder="Username" required data-parsley-type="alphanum" data-validate="checkNameAvailable" data-msg="Alphanumeric allowed only" />
</div>
</div>
<p>Password</p>
<div class="form-group">
<div class="col-sm-6">
<input type="password" class="form-control" id="Bpassword" name="Bpassword" placeholder="Password" />
</div>
</div>
<p>Re-type Password</p>
<div class="form-group">
<div class="col-sm-6">
<input type="password" class="form-control" id="Bpassowrd2" name="Bpassword2" placeholder="Retype Password"/>
</div>
</div>
</div>
</div>
The input <input type="text" class="form-control" id="Busername" name="Busername" placeholder="Username" required data-parsley-type="alphanum" data-validate="checkNameAvailable" data-msg="Alphanumeric allowed only" /> calls the checkNameAvailable function to make validation.
checkNameAvailable function:
Which makes an ajax call to check if the name is available or not.
function checkNameAvailable(el){
if($("#"+$(el).attr('id')).parsley().isValid()){
var data = $(el).val();
if($(el).attr('id') == "Busername"){
var type = "B";
}else{
var type = "I";
}
$.ajax({
method: "POST",
url: "isUserAvailableCommon",
async: false,
data: {Busername: data, _token: $("#_token").val(), _type: type },
success: function(msg) {
var retValue = {};
if(msg == "OK"){
retValue.status = true;
console.log(retValue);
return retValue;
}else{
retValue.status = false;
console.log(retValue);
return retValue;
}
}
});
}
}
The problem is that the variable retValue is not returned to the bootstrap-wizard validation.
However if i try like this it works but not when implementing with ajax
function checkNameAvailable(el){
var retValue = {};
retValue.status = false;
return retValue;
}
Any idea how to make it work with ajax? I have tried callbacks and methods described in Javascript function not waiting for AJAX responsebut it is still not working.

You can try to change your function like this:
function checkNameAvailable(el){
var dfd = $.Deferred();
if($("#"+$(el).attr('id')).parsley().isValid()){
var data = $(el).val();
if($(el).attr('id') == "Busername"){
var type = "B";
}else{
var type = "I";
}
$.ajax({
method: "POST",
url: "isUserAvailableCommon",
data: {Busername: data, _token: $("#_token").val(), _type: type },
success: function(msg) {
var retValue = {};
if(msg == "OK"){
retValue.status = true;
console.log(retValue);
dfd.resolve(retValue);
}else{
retValue.status = false;
console.log(retValue);
dfd.resolve(retValue);
}
}
});
}
return dfd.promise();
}
// after this you can use
// checkNameAvailable in this
// way.
checkNameAvailable(el).done(function(retValue) {
console.log(retValue);
});
Read my comment and example of function usage. When we using promise
the code can be asynchronous. You must not async: false - this is not
very good idea at all.
Edit:
Synchronous ajax request is not very good idea but existing code
base expect synchronous function so your function must be
changed in this way:
function checkNameAvailable(el) {
var result;
if ($("#" + $(el).attr('id')).parsley().isValid()) {
var data = $(el).val();
if ($(el).attr('id') == "Busername") {
var type = "B";
} else {
var type = "I";
}
$.ajax({
method: "POST",
url: "isUserAvailableCommon",
async: false,
data: {
Busername: data,
_token: $("#_token").val(),
_type: type
},
success: function(msg) {
var retValue = {};
if (msg == "OK") {
retValue.status = true;
console.log(retValue);
result = retValue;
} else {
retValue.status = false;
console.log(retValue);
result = retValue;
}
}
});
}
return result;
}
Good luck.
Edit 2:
I have forked the repository of project and add example how to use
asynchronous into validator function. This solution is kind of dirty
hack but is much better than using synchronous logic.
https://github.com/gonaumov/bootstrap-application-wizard/blob/master/demo/demoAsynchronousValidator.html
I also do a pull request with this changes.

Related

Highlight and append msg to element on return from .ajax

Upon ajax successful return, the return data contains status. if status is false(not ajax fail), return data contains array of element names and associated error message. The goal is to replicate .validate() error functionality by appending msg after element and highlight.
HTML form:
<form class="form-horizontal" id="chngPwdForm" action="changepwd.php" method="post">
.
. various HTML....
.
<div class="form-group">
<div class="alert alert-div font-weight-bold" id="errorTxt" role="alert" style="display:none;"> </div>
<label for="crntPwd">Existing Password:</label>
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key fa-fw"></i></span>
<input type="password" class="form-control" id="crntPwd" name="crntPwd" required>
</div>
</div>
.
. more HTML follows
.
JQUERY:
.
.yada, yada, yada
.
$("#chngPwdForm").submit(function(event){
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $("#chngPwdForm").attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var element;
var errorObj = new Error("");
$.each(data.Msg, function(elemName, errMsg) {
element = $("#chngPwdForm").filter("#" + elemName);
errorObj.message = errMsg;
$(element).closest(".form-group").addClass("has-error");
errorObj.insertAfter(element);
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})
.fail (function(response){
var Msg = "chngPwd call failed. errorThrown: " + response;
var obj = JSON.stringify(response);
alert("obj is: " + obj);
$('#chngPwdForm div[id="errorTxt"]').text(Msg);
})
}
else {
$('#chngPwdForm div[id="errorTxt"]').text('Please Correct errors').show();
}
return false;
The JSON response from changepwd.php:
{\"status\":false,\"Msg\":{\"crntPwd\":\"Current Password may only contain a-z, A-Z, 0-9, ! or #\"}
JS error
"TypeError: errorObj.insertAfter is not a function" is thrown for
"errorObj.insertAfter(element);"
The implemented solution:
JQuery:
// New Code has leading and trailing *
$("#chngPwdForm").submit(function(event){
*$(".chngPwderr").removeClass("error").text('');* //used to remove old messages
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $(this).attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var focusSet = false;
$.each(data.Msg, function(elemName, errMsg) {
*$("#" + elemName).attr("type", "text");
if (!$("#" + elemName).parent().hasClass("error")) {
$("#" + elemName).parent().append('<div class="chngPwderr error">' + errMsg + '</div>');
}
if (!focusSet) {
$("#" + elemName).focus();
focusSet = true;
}*
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})

how to validate 10 digit phone number?

I need to 10 digit number validation in JS code. I've put the "Contact already exists" validation code from the databse. But I'm not recognize the 10 digit validation code.
my js code:
function checkcontact() {
var contact=document.getElementById( "UserContact" ).value;
if(contact.length==10) {
$.ajax({
type: 'post',
url: 'index.php=checkemail',
data: {
u_contact:contact,
},
success: function (response) {
if(response=="not_exist") {
return true;
} else {
$( '#contact_status' ).html(response);
}
}
});
}
}
my input type from
<input class="form-control" type="text" maxlength="10" id="UserContact" onkeyup="checkcontact(); if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" placeholder="Contact Number Here" required/>
<span id="contact_status"></span> </div>
How to validate 10 digit number in checkcontact() function in js code ?
try this,
function checkcontact(){
var contact=document.getElementById( "UserContact" ).value;
var validate = check(contact);
if(validate){
$.ajax({
type: 'post',
url: 'index.php=checkemail',
data: {
u_contact:contact,
},
success: function (response) {
if(response=="not_exist"){
return true;
}
else{
$( '#contact_status' ).html(response);
}
}
});
}
}
function check(var number){
var reg = /^[0-9]{1,10}$/;
var checking = reg.test(number);
if(checking){
return true;
}else{
return false;
}
}
Try this..
var val = contact
if (/^\d{10}$/.test(val)) {
// value is ok, use it
} else {
alert("Invalid number; must be ten digits")
return false
}
Reference
Just use this to validate whether the string is only number or not
var yourValue = '123456789';
var isNumber = /^\d+$/.test(yourValue);
alert(isNumber);
Check this code
$(function() {
$('#UserContact').blur(function() {
var contact = $("#UserContact").val();
if(contact.length==10){
alert(contact)
//return false;
$.ajax({
type: 'post',
url: 'index.php=checkemail',
data: {u_contact:contact},
success: function (response) {
if(response=="not_exist"){
return true;
}
else
{
$( '#contact_status').html(response);
}
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input class="form-control" type="number" maxlength="10" id="UserContact" placeholder="Contact Number Here" required/>
<span id="contact_status"></span> </div>
You don't need to validate 10 digits, just bind with input type as Number.
It allow only numbers as an input.
As per your code when its length will be 10 so automatically it will call ajax.
<input class="form-control" type="number" maxlength="10" id="UserContact" onkeyup="checkcontact(); if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" placeholder="Contact Number Here" required/>
<span id="contact_status"></span>

Can not get ajax callback to a function

I have a form for user to register new account. I use jquery + ajax to check availability of email address on form submission. In Jquery code I used e.preventDefault(); to prevent form submission if there is any error occurs. I tried the existed email address in the email input and click submit the form. It allows form to submit. It should not do this because ajax reponseText return true means that the email address is already existed in database.
Could anyone please tell me how to fix my code so that if ajax response returns true, it will prevent form submission and shows up errors.
I tried to read and follow this article but fails after so many attempts.
Here is my form:
<form role="form" method="post" id="signupForm" action="index.php?view=signup-gv">
<div class="col-xs-6 border-right">
<div class="form-group">
<label for="exampleInputEmail1">Full Name</label>
<input type="text" class="form-control" id="regname" name="regname" placeholder="Full Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label><span id="emailcheck"></span>
<input type="email" class="form-control" id="regemail" name="regemail" placeholder="Enter email">
</div>
</div>
<div class="form-group col-xs-6">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="regpass" name="regpass" placeholder="Password">
</div>
<button style="position:relative; left: 15px; top: 10px;" class="btn btn-default" name="register" id="register">Register</button>
</form>
Here my jquery code:
$(document).ready(function(){
$('#regname').focus();
$('#signupForm').submit(function(e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
if(regname.val() == ''){
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
e.preventDefault();
}
else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
e.preventDefault();
}
else if(regpass.val() == ''){
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
e.preventDefault();
}
emailCheck().done(function(r){
if(r){
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
e.preventDefault();
}
});
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {regemail:regemail.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'emailcheck.php',
success: function(responseText){
if(responseText == 0){
return false; // good to go
}
else{
emailcheck.html('<span class="errorss"> This email is existed.</span>');
return true; // This email is registered. Please try different one
}
}
});
}
First you are not returning anything from the emailCheck() function, but you are using it as if it is returning a promise object.
So
$(document).ready(function () {
$('#regname').focus();
$('#signupForm').submit(function (e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
//prevent the form submit
e.preventDefault();
if (regname.val() == '') {
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
} else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
} else if (regpass.val() == '') {
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
} else {
emailCheck().done(function (r) {
if (r) {
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
} else {
$('#signupForm')[0].submit();
}
});
}
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {
regemail: regemail.val()
};
var deferred = jQuery.Deferred();
$.ajax({
type: 'POST',
cache: false,
data: UrlToPass,
url: 'emailcheck.php',
success: function (responseText) {
if (responseText == 0) {
deferred.resolve(false);
} else {
emailcheck.html('<span class="errorss"> This email is existed.</span>');
deferred.resolve(true);
}
},
error: function () {
deferred.reject();
}
});
return deferred.promise();
}
You are confusing yourself with sync and async functions. An ajax function makes an Async call and returns output in its callback. You are trying to wrap an Async function inside a normal function and expecting it to behave synchronously.
Your function returns before the Ajax call receives its output. Use
async: false
$.ajax({
type : 'POST',
cache: false,
async: false,
data : UrlToPass,
Refer to following for dettails:
How to make JQuery-AJAX request synchronous

Trigger event on submit

In a newsletter sign-up form, I would like to make the email disappear after the end user hits enter. I have already added JS to hide and unhide the placeholder text.
The code:
<form id="form" action="https://xxxx.com/subscribe/post-json?u=xxx&id=xx&c=?" method="GET">
<input type="hidden" name="u" value="xxx">
<input type="hidden" name="id" value="xxx">
<input id="email" type="EMAIL" autocapitalize="off" autocorrect="off" name="MERGE0" id="MERGE0" size="25" placeholder= "Type your email and press enter">
<p id="response"></p>
</form>
And the JS:
<script >
var text = document.getElementById("email");
text.onfocus = function() {
if ( text.placeholder == "Type your email and press enter") {
text.placeholder = "";
}
};
text.onblur = function() {
if ( text.placeholder == "") {
text.placeholder = "Type your email and press enter";
}
};
</script>
I tried to create a function to trigger the event but it still didn't work:
function checkEnter(event)
{
if (event.keyCode == 13) {text.placeholder = "cool";}
};
Could you all see what's wrong with my code?
Thank you.
You need to add a event listener for the enter key. You could remove your function checkEnter and use this instead:
document.querySelector('#email').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
if (key == 13) {
text.placeholder = "cool";
}
};
I have integrated the code below with the mailchimp form and got the desired results:
var paragraph = document.getElementById('response');
$('#form').submit(function(e) {
var $this = $(this);
$.ajax({
type: "GET", // GET & url for json slightly different
url: "https://xxxxx.com/subscribe/post-json?u=xxxx&id=xxx&c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
paragraph.innerHTML = data.msg;
text.placeholder = "Oopsy daisy! Error :-(";
form.reset();
} else {
paragraph.innerHTML = data.msg;
text.placeholder = "Thanks so much!";
form.reset();
}
}
});
return false;
});

Prevent AJAX form from submitting twice?

I can't figure out why this AJAX form is processing and sending out an email twice. Is there some sort of obvious hickup in the code you can see causing this to occur?
HTML
<form class="submit-form" method="post">
<input type="url" class="content-link" name="content_link" placeholder="Link" />
<input type="email" class="email" name="email" placeholder="Your Email Address" />
<button class="submit-modal-button submit-button"><span>Send<span class="ss-icon">send</span></span></button>
<p class="terms">By clicking Submit you agree to our Terms & Conditions</p>
</form>
JavaScript
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]'),
viewport_size = $(window).width() + "x" + $(window).height(),
user_browser = BrowserDetect.browser,
user_os = BrowserDetect.OS,
current_page = document.location.href;
$('.submit-form input[type="url"],.submit-form input[type="email"]').blur(function () {
if ($.trim($(this).val()) == '') {
$(this).addClass('form-validation-error');
return false;
} else {
$(this).removeClass('form-validation-error');
}
});
form.submit(function () {
if ($.trim(content_link.val()) == '' && $.trim(email.val()) == '') {
content_link.addClass('form-validation-error');
email.addClass('form-validation-error');
return false;
}
else if ($.trim(content_link.val()) == '') {
content_link.addClass('form-validation-error');
return false;
}
else if ($.trim(email.val()) == '') {
email.addClass('form-validation-error');
return false;
} else {
var env = TTB.getEnvironment();
$('.submit-modal-button').attr('disabled','disabled');
$(document).ajaxStart(function () {
$('.submit-modal .screen-1').delay(300).append('<span class="loading2"></span>');
});
$.ajax({
url: env.submit_modal_process,
type: 'POST',
data: {
    content_link: content_link.val(),
    email: email.val(),
viewportsize: viewport_size,
browser: user_browser,
os: user_os,
current_page: current_page
  },
success: function () {
$('.submit-modal .screen-1').delay(1000).fadeOut(300, function () {
$('.submit-modal .screen-1').fadeOut(500, function () {
$('span.loading2').detach();
$('.submit-modal .screen-2').fadeIn(500, function () {
$('.submit-modal .screen-2').append('<img class="carlton" src=' + env.the_environment + TTB.config.image_path() + 'submit-modal-success.gif' + ' />');
});
$('.submit-modal .screen-2').css('display','block').delay(4200).fadeOut(500, function () {
$('.carlton').hide();
$('.submit-modal .screen-1').fadeIn(500);
content_link.val('');
email.val('');
content_link.focus();
email.removeClass('form-validation-error');
$('.submit-modal-button').removeAttr('disabled');
});
});
});
}
});
return false;
}
});
}
EXAMPLE.processSubmitModal();
If to remove all non relevant to the issue code from your snippets we will get the following:
HTML
<form class="submit-form" method="post">
<input type="url" name="content_link" />
<input type="email" name="email" />
<button>Send</button>
</form>
JavaScript
$(function() {
var EXAMPLE = {
processSubmitModal : function () {
var form = $('.submit-form'),
content_link = $('.submit-form input[type="url"]'),
email = $('.submit-form input[type="email"]');
form.submit(function () {
$.ajax({
url: document.location.href,
type: 'POST',
data: {
content_link: content_link.val(),
email: email.val()
},
success: function () { // <-- The function that is executed twice
// Do something
}
});
return false;
});
}
};
EXAMPLE.processSubmitModal();
// And somewhere in the code that was not presented in snippet...
EXAMPLE.processSubmitModal();
});
I played around with your snippet and it always performs only one AJAX call and process email once except the only case - when somewhere in the code you call EXAMPLE.processSubmitModal() once again. Search in your code, I'm almost sure it is the reason. Pay attention that each time you call EXAMPLE.processSubmitModal() you add one another handler to submit event of the form and not override it.
Try like this
form.submit(function (event) {
if(event.handled !== true)
{
//put your ajax code
event.handled = true;
}
return false;
});
Refernce

Categories

Resources