I have this pop up where a user enters his email:
<form class="form" id="PopupEmailForm">
<div id="PopupEmail" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<a data-dismiss="modal">Close</a>
<p>Enter The Email:</p>
<input type="email" id="EmailInput" name="Email" placeholder="name#example.com" required="required" />
<input type="submit" value="Send" id="PopupEmailSubmit" />
</div>
</div>
</div>
</div>
</form>
On submit I am doing the following:
$('#PopupEmailSubmit').click(function () {
$.ajax({
type: "POST",
url: "controller/action",
data: {
Email: $('#EmailInput').val()
},
beforeSend: function () {
$("#PopupEmailSubmit").prop('disabled', true);
$.growl({
title: "Email Confirmation",
message: "Sending Email..."
});
},
success: function (res) {
if (res) {
$.growl.notice({ title: "Email Confirmation", message: "Email Sent!" });
$('#PopupEmail').modal('hide');
} else {
$.growl.error({ title: "Email Confirmation", message: "Email Not Sent. Try again later." });
}
$("#PopupEmailSubmit").prop('disabled', false); // enable button
}
});
});
I want to do a validation on the email input before I call the ajax post method.
And I want the validation to be similar(inline) to HTML5 validation for <input type="email"/>
Can anyone help
Since you are using a form, you could also do this in submit event of the form rather than click of the button
$('#PopupEmailForm').submit(function (event) {
event.preventDefault();
//ajax call here
});
Try this:
$('#PopupEmailSubmit').click(function () {
var email = $('#EmailInput').val();
// create a validation rule
if(validation successful)
{
// make ajax call
}
else
{
// show alert
}
});
Related
i'm creating a ajax post request that works fine. however to make it more appealing i'm trying to implement so that when the user click on #sign_in it will change the text while request is going on. if it result in error a message will appear. this message will automatically remove after a couple of seconds. however if u click .close it will force close. The issue is however that following does not work:
$(".alert a").click(function(e) {
$('.alert').fadeOut();
});
Nothing happens when i click on .close. in addition to this below does not work either.
$('#sign_in').val('Logger ind...');
Full Code
<form id="sign_in">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
</div>
<a href="#">
<small>Forgot password?</small>
</a>
<div class="form-group text-center add_top_20">
<input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
<div class="alert alert-error alert-danger" style="display: none;">
<a class="close" href="#">×</a>
Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
jquery
$("#sign_in").submit(function (event) {
// Change sign in button text
$('#sign_in').val('Logger ind...');
// post request
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "/account/login/auth/",
type: "POST",
dataType : 'json',
contentType: 'application/json',
data: {
'username': username,
'password': password
}, success: function (data) {
if (data.success) {
alert('success');
} else {
showAlert()
}
// Change sign in text back
$('#sign_in').val('Log ind');
}, error: function(error){
// Change sign in text back
$('#sign_in').val('Log ind');
}
});
});
function showAlert(){
if(!$('.alert').is(':visible'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
$(".alert a").click(function(e) {
$('.alert').fadeOut();
});
and all of this is wrapped in $(document).ready(function () {
Mmm, your event is launching but you need to use clearQueue in order to launch your fadeOut animation again interrupting the previous one.
$(".alert a").click(function(e) {
$('.alert').clearQueue();
$('.alert').fadeOut();
});
Change your form id or submit button id and change :visible to :hidden
function showAlert(){
if($('.alert').is(':hidden'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
Here I have change form 'id'
<form id="sign_in_form">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
</div>
<a href="#">
<small>Forgot password?</small>
</a>
<div class="form-group text-center add_top_20">
<input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
<div class="alert alert-error alert-danger" style="display: none;">
<a class="close" href="#">×</a>
Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
jQuery
$("#sign_in_form").submit(function (event) {
// Change sign in button text
$('#sign_in').val('Logger ind...');
// post request
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "/account/login/auth/",
type: "POST",
dataType : 'json',
contentType: 'application/json',
data: {
'username': username,
'password': password
}, success: function (data) {
if (data.success) {
alert('success');
} else {
showAlert()
}
// Change sign in text back
$('#sign_in').val('Log ind');
}, error: function(error){
// Change sign in text back
$('#sign_in').val('Log ind');
}
});
});
function showAlert(){
if($('.alert').is(':hidden'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
$(".alert a").click(function(e) {
$('.alert').clearQueue();
$('.alert').fadeOut();
});
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 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 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/
Working on static pages only.. no backend is present...Hi trying to navigate between html pages, and succeesful in that. But need to switch the page only when the form is properly validate, have tried but its not working..
Need some help...
HTML:
<div class="formContainer">
<form class="form" id="loginForm">
<div class="form-group">
<label>Login</label>
</div>
<div class="form-group">
<label for="loginForm-email">Email address</label>
<input type="email" class="form-control" id="loginForm-email" name="loginForm-email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="loginForm-password">Password</label>
<input type="password" class="form-control" id="loginForm-password" name="loginForm-password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
JS:
$(document).ready(function () {
var fnValidate = $("#loginForm").validate({
rules: {
"loginForm-email": {
required: true,
email: true
},
"loginForm-password": {
required: true,
minlength: 5
}
}
});
$('.btn').click(function(e) {
e.preventDefault();
if(fnValidate){
window.location.reload(true);
window.location.href = '../html/userPage.html';
}
else{
alert('hia');
}
});
});
The jQuery validator has custom success and failure callbacks which you can use.
As per your current approach, the fnValidate will return you an object. So you won't know whether it's validated or not. So try using the following approach.
$(document).ready(function () {
$("#loginForm").validate({
rules: {
"loginForm-email": {
required: true,
email: true
},
"loginForm-password": {
required: true,
minlength: 5
}
},
submitHandler: function () {
console.log("inside valid");
window.location.reload(true);
window.location.href = '../html/userPage.html';
// this.submit()
},
invalidHandler: function (event, validator) {
// 'this' refers to the form
console.log("Please fill the form");
}
});
});
jsfiddle example : http://jsfiddle.net/mohamedrias/2vvaN/2/
submitHandler is called only if the form is valid. So there you can submit the form.