How to call 2 javascript function simeltaneously - javascript

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.

Related

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

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

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()" />

Submit form button stuck after ajax post

Hi i have a form which uses Ajax to make a post in Rails 4. The javascript runs some validation and should return an alert message once the post is successful. Currently the submit button stays depressed and although the form posts no message gets alerted. I dont know what i'm doing wrong and just want the form to alert a message and then reset itself.
$('#submit1').click(function(e){
e.preventDefault();
var name = $('input#name').val();
if (name == "") {
alert("please enter a name!");
$('input#name').focus();
return false;
}
var email = $('input#email').val();
if (email == ""){
alert("please enter your email");
$('input#email').focus();
return false;
}
var content = $('textarea#text').val();
if (content == ""){
alert("please enter a comment");
$('textarea#text').focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&content=' + content;
$.ajax({
type: "POST",
url: "emailer",
data: dataString,
dataType: 'json',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
success: function(){
alert("mappy jappy");
$('input#name').reset();
$('input#email').reset();
$('textarea#text').reset();
}
});
return false;
});
You are preventing the wrong event. You need the 'onsubmit' event of the form not the 'onclick' event of the submit button.
$('#myform').on('submit', function(event){
event.preventDefault();
/* your code here */
});
For more info please read :
How to prevent form from being submitted?
First of all the reset function is not for the text boxes..it will run for the form. So the corrected code would be...
<script>
$(function(){
$('#submit1').click(function(e){
e.preventDefault();
var name = $('input#name').val();
if (name == "") {
alert("please enter a name!");
$('input#name').focus();
return false;
}
var email = $('input#email').val();
if (email == ""){
alert("please enter your email");
$('input#email').focus();
return false;
}
var content = $('textarea#text').val();
if (content == ""){
alert("please enter a comment");
$('textarea#text').focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&content=' + content;
$.ajax({
type: "POST",
url: "user_availability.php",
data: dataString,
dataType: 'json',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
success: function(){
alert("mappy jappy");
$('#contact-form')[0].reset();
}
});
return false;
});
});
</script>
AND the html part would be like below-
<form id="contact-form" method="post" enctype="multipart/form-data">
<input type="text" id="email" name="email" />
<input type="text" id="name" name="name" />
<textarea name="text" id="text"></textarea>
<input type="submit" value="submit" id="submit1" />
</form>
Please Check and let me know...

Categories

Resources