Can not get ajax callback to a function - javascript

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

Related

onsubmit return false is not working

The following script shows the error message correctly, but the form always submits whether confirm_shop_code() returns true or false. I tried in many ways to solve the bug but it still persists. I have to stop the form from submitting when it returns false, but allow it to submit when it returns true. Please can any one help me to solve this?
<h2 id="shop_data"></h2>
<!-- form -->
<form action="" class="form-horizontal form-label-left input_mask" method="post" onsubmit="return confirm_shop_code();">
<div class="col-md-4 col-sm-4 col-xs-8 form-group">
<input type="text" class="form-control" id="shop" name="code" value="<?php echo $account->code; ?>" placeholder="Enter Shop Code">
</div>
</form>
<!-- validation script -->
<script>
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
return true;
} else {
return false;
}
}
});
} else {
$( '#shop_data' ).html("");
return false;
}
}
</script>
<!-- php code -->
<?php
include "system_load.php";
$code = $_POST['shop_code'];
global $db;
$query = "SELECT code from accounts WHERE code='".$code."'";
$result = $db->query($query) or die($db->error);
$count = $result->num_rows;
if($count > 0) {
echo "SHOP CODE already Exists";
} else {
echo "OK";
}
exit;
?>
The reason it is submitting is because AJAX calls are asynchronous by default. I wouldn't suggest making it synchronous because this will block the rest of the javascript execution. Also, you are returning false from the success method of $.ajax. This is not in the same scope as the parent function and therefore does not also cause the parent function to return false. So in fact, your confirm_shop_code() function is not returning anything unless code is false and that's why your form is always being submitted, no matter what happens with the AJAX call.
I would recommend using jQuery to bind to the form's submit event and just disable form submitting with preventDefault(). First, just add an id attribute to the form (e.g. "yourform") and do something like:
$("form#yourform").submit(function(e) {
e.preventDefault();
var form = $(this);
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
form.unbind('submit').submit()
}
}
});
} else {
$( '#shop_data' ).html("");
}
});
You need to add async:false to your ajax code
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
var stopSubmit = false;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
async:false,
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
stopSubmit = false;
} else {
stopSubmit = true;
}
}
});
} else {
$( '#shop_data' ).html("");
stopSubmit = true;
}
if(stopSubmit){
return;
}
}
You should call return false; function on the click event of the submit button.
<button type="submit" id="submit" onclick="return false;" class="btn btn-primary col-4">Proceed</button>
or you can use:
document.getElementById("submit").addEventListener("click", function (e) {
//your logic here
//this return false will not work here
return false;
//this will work
e.preventDefault();
});

How to call 2 javascript function simeltaneously

I want to check emailid format as well as check weather that email id exists in the database simultaneously as soon as the user moves to next field.
MY HTML CODE:
<input type="email"
name="mail"
placeholder="Email Address"
required="required"
onkeyup="checkuser(this.value)"
onblur="validateEmail(this);"/>
MY JAVASCRIPT CODE:
function chckuser(val)
{
$.ajax({
type:"POST",
url:"checkuser.php",
data: 'mail='+val,
success: function(data){
$("#msg").html(data);
}
});
}
function validateEmail(emailField){
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false)
{
alert('Invalid Email Address');
return false;
}
return true;
}
You should runs these 2 functions inside another function.
Example:
function handleBlur(emailField) {
if ( ! validateEmail(emailField)) { return false; }
chckuser(emailField.value);
}
function chckuser(val)
{
$.ajax({
type:"POST",
url:"checkuser.php",
data: 'mail='+val,
succss: function(data){
$("#msg").html(data);
}
});
}
function validateEmail(emailField){
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false)
{
alert('Invalid Email Address');
return false;
}
return true;
}
<input type="email" name="mail" placeholder="Email Address" required="required" onblur="handleBlur(this);"/>
Since Javascript is run in one thread in the browser you cannot do two things at same time. However I would first check just the email address format, if it is valid then make call to the back-end to check if it exists.

Javascript not waiting for ajax with bootstrap-wizard.js

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.

why $.ajax is not getting data?

I want to validate form and then send the values using $.ajax .but it shows Undefined index: is_ajax. why it does not get form_data? why it happens?What change should be done?
here is my script
function validateForm()
{
var oldPassword = document.forms["dsettings"]["oldPassword"].value;
var newPassword = document.forms["dsettings"]["newPassword"].value;
var retypePassword = document.forms["dsettings"]["retypePassword"].value;
if (document.forms["dsettings"]["oldPassword"].value == null || oldPassword == "") {
alert("Enter old password");
return false;
}
else if (document.forms["dsettings"]["newPassword"].value == null || newPassword == "") {
alert("Enter new password");
return false;
}
else if (document.forms["dsettings"]["retypePassword"].value == null || retypePassword == "") {
alert("Retype new password");
return false;
}
else if ( newPassword != retypePassword) {
alert("Retype new password correctly");
return false;
}
else
{
var action = $("#dsettings").attr('action');
var form_data = {
oldPassword: $('#oldPassword').val(),
newPassword: $('#newPassword').val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == "success")
$("#message").html('<p class="success">Successfully changed password!</p>');
else if(response == "wrong_old_password")
{
$("#message").html('<p class="error">Wrong old password!type again!</p>');
}
else
{
$("#message").html('<div class="error">update error.Try again! !</div>');
}
}
});
}
}
my html code
<button type="submit" id="submit" name="submit" onclick="return validateForm()" class="form-submit" >submit</button>
and php code
<?php $is_ajax = $_REQUEST['is_ajax'];
// some codes ?>
Since this seems to be your very first post and very ugly , you need to clean it something like this (which is not perfect either !)
Provide as much as data as possible e. g
HTML
<form action="fakeurl.com" method="post" name="dsettings" id="dsettings" >
<ul>
<li>Old Password: <input type="password" name="oldPassword" /></li>
<li>New Password: <input type="password" name="newPassword" /></li>
<li>Retype New Password: <input type="password" name="retypePassword" /></li>
<li><input type="submit" name="submit" value="Change Password" /></li>
<li><div id="message"/></li>
</ul>
</form>
Javascript
$(document).ready(function(){
$('#dsettings').on('submit',function(event){
changePassword(this)
event.preventDefault();
});
});
function validateChangePassword(frm){
var oldPassword=frm["oldPassword"].value
var newPassword=frm["newPassword"].value
var retypePassword =frm["retypePassword"].value;
if (oldPassword.trim()=="") {
$('#message').html("<p class='error'>Enter old password</p>");
return false;
}
else if (newPassword.trim()=='') {
$('#message').html("<p class='error'>Enter new password</p>");
return false;
}
else if (retypePassword.trim() == "") {
$('#message').html("<p class='error'>Retype new password</p>");
return false;
}
else if ( newPassword != retypePassword) {
$('#message').html("<p class='error'>Retype new password correctly</p>");
return false;
}
else
return true;
}
function changePassword(frm){
if(validateChangePassword(frm)){
var url = $(frm).attr('action');
var data = {
oldPassword: $(frm).find('input[name="oldPassword"]').val(),
newPassword: $(frm).find('input[name="newPassword"]').val(),
retypePassword: $(frm).find('input[name="retypePassword"]').val(),
is_ajax: 1
};
ajaxPost(url,data);
}
return false;
}
function ajaxPost(post_url,post_data){
$.ajax({
type: "POST",
url: post_url,
data: post_data,
success: function(response)
{
if(response == "success")
$("#message")
.html('<p class="success">Successfully changed password!</p>');
else if(response == "wrong_old_password")
{
$("#message")
.html('<p class="error">Wrong old password!type again!</p>');
}
else
{
$("#message")
.html('<div class="error">update error.Try again! !</div>');
}
}
});
}
DEMO
Possible Issues
Avoid using custom js and jquery mix
I suspect you provided any id to element e.g $('#oldPassword').val()
There is good plugin for form validation use that one
Try to change your code on function call with parameter:
function validateForm(e) {
e.preventDefault();
and here:
<button type="submit" id="submit" name="submit" onclick="validateForm(this); return false;" class="form-submit" >submit</button>
From the answers you've given in the comments, what's almost certainly happening is that:
You are not preventing the default submit behavior, so the default submit behavior is taking place
There is an error somewhere in your code that is causing your validateForm() function to fail and for your $.ajax to never run
To troubleshoot this:
Change your button to type="button".
Open up your JS console (you can usually do this by pressing F12 and clicking the Console tab)
See if there are any errors in the console.
Once you figure out what the error is, you should:
Stop using onclick handlers and unobtrusively set up events
Use preventDefault() to prevent default submit events
$(function () {
$("#submit").click(function (e) {
e.preventDefault();
validateForm();
});
});
Include jquery-1.4.3.min.js file before validateForm function call.
<input type="button" name="submit" value="Change Password" onclick="validateForm()" />

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

Categories

Resources