i am trying to perfom form validation before submit to server. I am using jquery.validate plugin
(JQuery validation plugin page)
The problem i am facing is that does not matter what i type in the form fields, validation always succeded, i double checked everything against documentation and samples over the wire and cannot see why i am getting this behaviour.
This form is loaded via jquery ajax:
$.ajax({
url: "mypage.php",
type: "POST",
cache: false,
success: function(cont){
$("body").append(cont);
}
});
Here i show you mypage.php code
<script src="js/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#frmParticipante").validate({
rules: {
nombre: { required: true } ,
email: { required: true, email: true },
ci: { required: true}
}
});
$("#frmParticipante").submit(function(e){
e.preventDefault();
if($(this).valid()){
loadpop("ganaste.php");
}
else
loadpop("perdiste.php");
});
});
</script>
<div id="pop_terminaste" class="pop_mensaje ingresardatos animated fadeInDown">
<div id="infopop">
<div id="lady"> <img src="images/terminaste1.jpg" width="453" height="626" /> </div>
<div id="dato">
<p class="txt1">¡Terminaste la trivia!</p>
<p class="txt2">Ahora solo te falta completar tus datos para conocer el resultado.</p>
<p class="txt3">Si ha cargado anteriormente sus datos, ingresar solo su cédula.</p>
<form action="" id="frmParticipante" class="form">
<fieldset>
<label for="nombre"><img src="images/ico_nombre.png" alt="ico_nombre" /></label>
<input type="text" placeholder="Nombre y Apellido" id="nombre">
</fieldset>
<fieldset>
<label for="email"><img src="images/ico_email.png" alt="ico_email" /></label>
<input type="text" placeholder="Email" id="email">
</fieldset>
<fieldset>
<label for="ci"><img src="images/ico_ci.png" alt="ico_ci" /></label>
<input type="text" placeholder="C.I" id="ci">
</fieldset>
<p class="msg error">Favor verificar los datos ingresados.</p>
<input type="submit" value="VER RESULTADOS" />
</form>
</div>
</div>
</div>
Thanks
I am pretty sure that the validation library requires name attributes and doesn't pay attention to id attributes. You should either change your id attr's to name, or just add name attributes with the same values...like :
<input type="text" placeholder="Nombre y Apellido" id="nombre" name="nombre">
Here is a fiddle to show that it works http://jsfiddle.net/7WTvL/1/
Along with the names, you will likely need to load your validate.js library in the head of the page you are loading the form into, and then run validate in .done() on your ajax request.
<script>
$.ajax({
url: "mypage.php",
type: "POST",
cache: false
}).done(function(cont) {
$("body").append(cont);
$("#frmParticipante").validate({
rules: {
nombre: { required: true } ,
email: { required: true, email: true },
ci: { required: true}
}
});
});
$("#frmParticipante").submit(function(e){
e.preventDefault();
if($(this).valid()){
loadpop("ganaste.php");
}
else
loadpop("perdiste.php");
});
</script>
Again...make SURE the validate library is loaded on the page you're ajax'ing content into...it needs to be on the page before your ajax'd content arrives.
Related
I have created the code for save data in my custom table using Ajax which is working fine.
After that I want to post these data on the asp.Net API using js/jQuery. How I can post same data on the aps.net.
Here is my HTML form and JS code:
<div id="inline1" class="audit-form" style="display: none;">
<form class="infusion-form" id="infusion-form">
<h3 style="color: #002046;">Sign Up For a Free Capability Audit </h3>
<div class="dis_block clearfix">
<div class="form-group">
<label>First Name *</label>
<input required class="form-control" id="inf_field_FirstName" name="inf_field_FirstName" type="text" />
</div>
<div class="form-group">
<label>Last Name *</label>
<input required id="inf_field_LastName" name="inf_field_LastName" type="text" class="form-control" />
</div>
<div class="form-group">
<label>Email *</label>
<input required id="inf_field_Email" name="inf_field_Email" type="email" class="form-control" />
</div>
<div class="form-group">
<label>Confirm Email *</label>
<input required id="inf_field_Phone1" name="inf_field_Phone1" type="email" class="form-control" />
</div>
<div class="form-group" style="text-align: center;">
<input type="hidden" name="action" value ="save_procurement_data" />
<input type="submit" id="frm_basic_info" class="btn custom-btn" value="NEXT" />
</div>
</div>
</form>
</div>
JS Code is here
<script type = "text/javascript">
jQuery(document).ready(function() {
jQuery(document).on('click', '#frm_basic_info', function(e){
jQuery("#infusion-form").validate({
rules: {
inf_field_FirstName: "required",
inf_field_LastName: "required",
inf_field_Email: "required",
inf_field_Phone1: {
equalTo: inf_field_Email
}
},
messages: {
inf_field_FirstName: "Please enter your firstname",
inf_field_LastName: "Please enter your lastname",
inf_field_Email: "Please enter your email",
inf_field_Phone1: "Please enter your confirm email correct",
},
submitHandler: function (form) {
e.preventDefault();
var frmd = new FormData();
var save_data = jQuery('form').serializeArray();
jQuery.each(save_data,function(key,input){
frmd.append(input.name,input.value);
});
jQuery.ajax({
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: frmd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
return false;
//window.location.href = "<?php echo site_url(); ?>/about-your-organization";
}
});
}
});
});
});
</script>
In the alert I getting alert data saved success fully.
Simply add one more ajax method after saving in your php Url.
See, in your above ajax success method, check the status then post to Asp.Net Web Api, just like my bellow code,
success: function(data){
//Here you can check the data and call your Web Api. For example
if(data == "data saved success fully")
{
//Write an ajax method to post data to Web Api
$.ajax({
url: 'YourWebApiUrlHere',
data: frmd,
type:'Post',
success: function (data) {
//Show an alert message here that data saved in Web Api blah blah
if(data == "Your response from Web Api goes here")//Edit this message
alert("Data saved using Web Api");
else
alert("Failed to save data using Web Api");
}
error: function(xhr, status, error) {
alert(xhr.responseText); //This is the exception if any issue with server
}
})
}
else
alert("Your data haven't saved in Php Url. Check with server");
return false;
}
Hope it helps!
I have created forms using php and using jquery for validation.What i exactly need is if validation successful on submit button, disable the submit button till submission gets over.Here is my code:
if(document.location.pathname == "/contact-us"){
$("#form-contact-user").validate({
ignore: [],
rules: {
name:{
required: true
},email: {
email: true
},
phne: {
phnDash: true
},
zip: {
zipcode: true
}
},
errorPlacement: function(error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo( element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address")
{
error.appendTo(element.parent().parent().parent());
}
else{
error.insertAfter(element);
}
}
});
Try this:
$('#btnId').attr('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="btnId" value="Submit">
I hope this is what you are looking for,
$('#submitBtn').click(function(event) {
//event.preventDefault();
$(this).attr('disabled', true);
//Perform Validation
//if(valid) {
// $("#form-contact-user").submit();
//}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="submitBtn" value="Submit">
According to the documentation you can use:
submitHandler (default: native form submit):
Callback for handling the actual submit when the form is valid.
ANSWER UPDATED
From your comment:
Getting the following error:-Uncaught TypeError: Cannot read property 'call' of undefined
This message depends on your rules. Because I don't know anything about your
html I can also assume a possible structure in the following snippet:
$("#form-contact-user").validate({
debug: true,
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true
},
phone: {
required: true
},
zip: {
required: true
}
},
errorPlacement: function (error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo(element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address") {
error.appendTo(element.parent().parent().parent());
}
else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
// do other things for a valid form
$(form).find(':submit').prop('disabled', true);
setTimeout(function() {
form.submit();
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="form-contact-user" method="get" action="">
<fieldset>
<legend>Please provide your name, email address, phone number and zipcode</legend>
<p>
<label for="name">Name (required, at least 2 characters)</label>
<input id="name" name="name" type="text">
</p>
<p>
<label for="email">E-Mail (required)</label>
<input id="email" type="email" name="email">
</p>
<p>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="text" name="phone">
</p>
<p>
<label for="zip">Zip code (required)</label>
<textarea id="zip" name="zip"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
I have one subscription form with ajax. The problem is that success and error messages are always on the page. Why they are on the page and how to hide them until form is submitted?
This is my js function
$(document).ready(function(){
(function($) {
"use strict";
// validate subscribeForm form
$(function() {
$('#subscribeForm').validate({
rules: {
name: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
}
},
messages: {
name: {
required: "Please enter your name?",
minlength: "Your name must consist of at least 4 characters"
},
email: {
required: "Please enter your email address"
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"subscribe.php",
success: function() {
$('#subscribeForm :input').attr('disabled', 'disabled');
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#sub_success').fadeIn();
});
},
error: function() {
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$('#sub_error').fadeIn();
});
}
})
}
})
})
})(jQuery)
})
And this is the form
<div class="footer-newsletter row footer-widget right-box">
<h3 class="footer-title">newsletter sign up</h3>
<form class="form-inline newsletter-form" id="subscribeForm" method="post" action="">
<input type="text" id="name" name="name" class="form-control" placeholder="Name">
<input type="email" id="email" name="email" class="form-control" placeholder="Email">
<button type="submit" class="btn btn-primary" name="sub_submit">Submit</button>
</form>
<div id="sub_success">You subscribe succesfully!</div>
<div id="sub_error">Opps! There is something wrong. Please try again</div>
</div>
So sub_success and sub_error are always on the page..
Change this following things in your code:-
<div id="sub_success" style="display:none">You subscribe succesfully!</div>
<div id="sub_error" style="display:none">Opps! There is something wrong. Please try again</div>
use this type alert it will gone in 3sec
$('#success_message').fadeIn(1000).html("<div class='alert alert-danger' role='alert' style='font-size: 15px;'>Soory some there is some error,please enter again data...</div>").fadeOut(3000);
Just add .hide on document.ready for both elements as below:
$(document).ready(function(){
$('.sub_success,.sub_error').hide();
});
You could just write a css
#sub_success, #sub_error {display:none}
then with jquery you can just show and hide by using
$("#sub_success").show();
$("#sub_error").hide();
I am trying to custom mailchimp signup form.
I want to the form not got to the mailchimp landing page, after the form submit. I want it reload the form and display the message, if the submission success or failed.
I have tried what have been discussed on https://stackoverflow.com/a/15120409, but it is failed.
This my html & javascript for the form :
//newsletter -start
var $form = $('#mc-embedded-subscribe-form');
if ( $form.length > 0 ) {
$('form button[type="submit"]').bind('click', function ( event ) {
if ( event ) event.preventDefault();
register_newsletter($form);
return false;
});
}
function register_newsletter($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: {EMAIL:.find('#mce-EMAIL').val()},
//data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result == "success") {
$( "#mc-embedded-subscribe-form .form-group, #mc-embedded-subscribe-form button" ).remove();
$( "#mc-embedded-subscribe-form" ).append('<p>Pendaftaran Anda berhasil.</p>');
} else {
$( "#mc-embedded-subscribe-form .form-group, #mc-embedded-subscribe-form button" ).remove();
$( "#mc-embedded-subscribe-form" ).append('<p>Pendaftaran anda <strong>gagal</strong>.</p>');
}
}
});
}
//newsletter -end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-sub">
<div class="row">
<div class="col-md-24 col-sm-24 col-xs-24">
<div id="mc_embed_signup">
<p><strong>Daftar & Dapatkan VOUCHER 75,000<br/>serta penawaran spesial dari MatahariMall</strong></p>
<form action="http://mataharimall.us10.list-manage.com/subscribe/post-json?u=ce402de87bc4303ab82a36695&id=912ec37292&c=?" class="form-search-opps" id="mc-embedded-subscribe-form" method="post" name="mc-embedded-subscribe-form" novalidate="" role="search" target="_blank">
<div class="form-group">
<input class="form-control" id="mce-EMAIL" name="EMAIL" placeholder="Masukkan email Anda di sini" type="text" value="" />
</div>
<button class="btn btn-red pria" id="mce-GENDER-0" name="GENDER" type="submit" value="Pria">Pria</button>
<button class="btn btn-red wanita" id="mce-GENDER-1" name="GENDER" type="submit" value="Wanita">wanita</button>
</form>
</div>
</div>
</div>
</div>
If success, mailchimp will produce this :
?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."})
If failed, mailchimp will produce this :
?({"result":"error","msg":"0 - An email address must contain a single #"})
I am trying to validate form fields like, Name (must not be blank), Email_id(must be valid), Mobile(Must be valid). After the filling the all info I have to send this information to server, and redirect response to different page. Here nothing is working,
my form.html
<form class="form-horizontal" id="scheduleLaterForm" name="scheduleLaterForm">
<div class="col-lg-8">
<div class="fieldgroup">
<label class="col-lg-3 control-label" for="userName">Name:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style=" height: 30px;" class="form-control" id="userName" name="userName"
placeholder="Full Name" value="" type="text" required>
</div>
</div>
<div class="fieldgroup">
<label for="email" class="col-lg-3 control-label">Email:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style="height: 30px;" class="form-control" name="email"
id="email" placeholder="you#example.com" value=""
type="text" required>
</div>
</div>
<div class="fieldgroup">
<label for="userContactNumber" class="col-lg-3 control-label">Mobile:<font
style="color: red;">*</font></label>
<div class="col-lg-9">
<input style="height: 30px; width:100%;" class="form-control" id="userContactNumber"
name="userContactNumber" placeholder="Mobile Number"
onkeypress="enableKeys(event);" maxlength="10" type="text" required>
</div>
</div>
<div class="fieldgroup">
<label class="col-lg-3 control-label"></label>
<div class="col-lg-7">
<input type="submit" value="Register" id="btnBooking" class="submit">
</div>
</div>
</div>
</form>
script for validating form and sending data
<script>
$(document).ready(function(){
$("#scheduleLaterForm").validate({
rules: {
userName: "required",
email: {
required: true,
email: true
},
userContactNumber: "required"
},
messages: {
userName: "Please enter your Name",
userContactNumber: "Please enter your Mobile number",
email: "Please enter a valid email address",
},
submitHandler: function(form) {
// get values from textboxs
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('#userContactNumber').val();
$.ajax({
url:"http://localhost/services/bookService4Homes.php",
type:"GET",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
alert("success");
//alert(JSON.stringify(response));
},
error: function(err){
alert("fail");
//alert(JSON.stringify(err));
}
});
return false; // block regular submit
}
});
});
</script>
Php code
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","root");
mysql_select_db("service4homes");
if(isset($_GET['type']))
{
if($_GET['type']=="booking"){
$name = $_GET ['Name'];
$mobile = $_GET ['Mob_Num'];
$mail = $_GET ['Email'];
$query1 = "insert into customer(cust_name, cust_mobile, cust_email) values('$name','$mobile','$mail')";
$result1=mysql_query($query1);
}
}
else{
echo "Invalid format";
}
?>
You do not need an external click handler because the plugin automatically captures the click (of a type="submit") and blocks the submit.
You need an input or button in your form that is type="submit", otherwise the plugin will not be triggered at all.
You cannot have an external .ajax function while you have form.submit within the submitHandler of your .validate() method. This means the plugin is trying to submit the form while your click handler is trying to use ajax. They both cannot work at the same time. As per docs, any ajax belongs inside the submitHandler, and it's "the right place to submit a form via Ajax after it is validated".
You don't need to check form validity because when you use the built in submitHandler, this is also done automatically.
The jQuery4U code is nothing but complicated junk; everything can be simplified greatly. It serves no useful purpose other than to cause more confusion to those seeking guidance. It comes from a popular, yet poorly explained, online demo/tutorial by Sam Deering that is linked to/from many places.
$(document).ready(function(){
$("#register-form").validate({
rules: {
userName: "required",
email: {
required: true,
email: true
},
userContactNumber: "required"
},
messages: {
userName: "Please enter your Name",
userContactNumber: "Please enter your Mobile number",
email: "Please enter a valid email address",
},
submitHandler: function(form) {
// get values from textboxs
var uName = $('#userName').val();
var mailId = $('#addressemailId').val();
var mobNum = $('#userContactNumber').val();
$.ajax({
url:"http://192.168.1.11/services/bookService4Homes.php",
type:"POST",
dataType:"json",
data:{type:"booking",Name:uName, Email:mailId, Mob_Num:mobNum },
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(response){
//alert(JSON.stringify(response));
},
error: function(err){
//alert(JSON.stringify(err));
}
});
return false; // block regular submit
}
});
});
DEMO: http://jsfiddle.net/mh6cvf2u/