jquery validation and ajax form submit - javascript

I have problem with jquery validation and ajax form submit.
Here's validation code:
$(function() {
$("#contact-form").validate({
rules: {
name: {
required: true,
minlength: 2,
maxlength: 32
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 20
}
},
messages: {
name: {
required: "Please, enter a name",
minlength: $.format("Keep typing, at least {0} characters required"),
maxlength: $.format("Whoa! Maximum {0} characters allowed")
},
email: {
required: "Please, enter an email",
email: $.format("Please, enter valid email")
},
message: {
required: "Please, enter a message",
minlength: $.format("Keep typing, at least {0} characters required")
}
},
submitHandler:function(form) {
form.submit();
}
});
});
Here's ajax code for submitting the form:
$(document).ready(function(){
$('#contact-form').on('submit',function(e) {
$('#name').val('Your Name');
$('#email').val('Your Email');
$('#message').val('Your Message');
$.ajax({
url:'',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(10000);
},
error:function(data){
$("#error").show().fadeOut(10000);
}
});
e.preventDefault();
});
});
What I try to do is form validation and then submit the form. After submit the form should appear again with initial values.
The problem is that when I remove ajax then validation works fine, but I need ajax code to re-display the form.
How I could make this two pieces of code work together?

Place your ajax call within the submitHandler function:
submitHandler:function(form) {
//form.submit();
$.ajax({
url:'', //you will need a url surely, perhaps $(form).attr('action');
data:$(form).serialize(),
type:'POST',
success:function(data){
console.log(data);
$('#name').val('Your Name');
$('#email').val('Your Email');
$('#message').val('Your Message');
$("#success").show().fadeOut(10000);
},
error:function(data){
$("#error").show().fadeOut(10000);
}
});
}

Related

Alert function not working after ajax call in laravel

<script>
$(function () {
$("#portal_register_post").validate({
rules: {
user_email: {
required:true,
email: true,
maxlength: 50
},
CreatePwd: {
required:true,
maxlength: 50,
minlength: 8,
pwcheck:true
},
confirmpassword: {
required:true,
equalTo: "#CreatePwd"
}
},
messages: {
user_email: {
required: "Please Enter E-mail",
},
CreatePwd: {
required: "Please Enter Password",
},
confirmpassword: {
required: "Please Enter Confirm Password",
}
},
submitHandler: function(form) {
var $form_id = '#register_post';
var form = document.forms.namedItem("register_post");
var formdata = new FormData(form);
var $inputs = $($form_id+' :input:not(input[name=_token] :input)');
$inputs.prop("disabled", true);
request = $.ajax({
async: true,
type: "POST",
dataType: "json",
contentType: false,
url: "{{ URL::to('/portal/register') }}",
data: formdata,
processData: false,
success: function (result) {
alert(result);
},
timeout: 1000000
});
request.always(function () {
$inputs.prop("disabled", false);
});
}
});
});
</script>
route:
Route::get('/portal/register', 'PortalController#register');
Route::post('/portal/register', ['as' => 'portal.register.post', 'uses' => 'PortalController#postRegister']);
In the above code I am simply want to get response in my alert function after ajax success but what happen when I click on form submit button then it show status code: 302 and not able to get response in alert function. I don't know where I am doing wrong? Please help me to solve this.
Thank you

How to Add ajax form processing for html mail form

I currently finished creating ( modify a themeforest template ) a website and all i need to do now is to set up contact form to receive mail from my customers
/* *****************************************************************
* FORM VALIDATION
* ************************************************************** */
$("#contactForm").validate({
rules: {
fullname: {
required: true
},
email: {
required: true,
email: true
},
message: {
required: true
}
},
messages: {
fullname: {
required: "Please enter your name"
},
email: "Please enter a valid email address",
message: "Please enter your message"
},
submitHandler: function () {
// Add your ajax form processing here.
}
});
This is the code form config.js file. How do i set up with my mail ( contact#website.com )
$.ajax({type:'POST', url: 'contact.php', data:$('#contactForm').serialize(), success: function(response) { $('#contactForm').find('.form-control').html(response);}});
this is the final syntax that works perfectly
try this
var data = new FormData($("#contactForm")[0]);
$.ajax({
url : 'your url ',
type : 'post',
data : data,
mimeType : 'multipart/form-data'
contentType: false,
processData: false,
success: function(data){
}
});

Form Validation with Success

When I submit the form without filling in any information it quickly displays the error message then fades. I only want the form to fade if there's no error messages and the validation is successful. I think I may need to use an if statement for success or something to do with a submit handler?
So far I have this - https://jsfiddle.net/wnmLmcm8/
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: {
name: $('#name').val(),
email: $('#email').val()
},
success: function () {
$('#emailform').fadeOut("slow");
}
});
});
$("form").validate({
rules: {
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
}
}
});
});
Here is a working version of your jsFiddle: https://jsfiddle.net/ywhpdLen/3/
This snippet works, based off of your jsFiddle, but your jsFiddle does not work. I had to pull the code into my own dev environment, locally.
The popup stays until you click in the text field.
Adding "required" to the input elements & using the default ".validate()" extension does the job. If you're looking to customize it, I'd highly recommend looking at https://jqueryvalidation.org/documentation/
<div id="emailform">
<form method="post" action="form.php">
<hr>
<label for="name">Name</label>
<br>
<input type="text" name="name" id="name" class="NewsLetter1" required/>
<br>
<label for="email">Email</label>
<br>
<input type="text" name="email" id="email" class="NewsLetter2" required/>
<input type="submit" value="Submit">
<hr>
</form>
</div>
<script>
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: {
name: $('#name').val(),
email: $('#email').val()
},
success: function () {
$('#emailform').fadeOut("slow");
},
failure: function (ex) {
}
});
});
$("form").validate();
});
</script>
Per comments, below: It looks like your ajax call is still happening and form.submit() is firing off. You may want to remove your form.submit() call and include it in the validate call, like so.
$("form").validate({
submitHandler:function(form){
$.ajax({....})
}
});
Do it with submit handler like...
$(document).ready(function ()
{
$("form#sub_form").validate({
rules: {
UserName: "required",
Useremail: {
required: true,
email: true
},
Userpwd:{
required: true,
minlength:8
},
Con_Userpwd:{
required:true,
equalTo:"#reg-pass"
},
contact:{
required:true,
minlength:10
}
},
messages: {
UserName: "Please specify your name",
Useremail: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name#domain.com"
},
Userpwd:{
required: "Enter Your Password",
minlength:"Please Enter minimum 8 digit password"
},
Con_Userpwd: {
required:"Please re-enter your password",
equalTo:"Password not matched"
},
contact:{
required:"Phone Number Required",
minlength:"Minimum 10 Digits Required"
}
},
submitHandler: function(form) {
var msg = $("form#sub_form").serialize();
$.ajax({
type: "POST",
url: "register_checkout.php",
data: msg,
success: function (html) {
$(".popup").delay(5000).fadeOut(1500);
setTimeout(function(){window.location='one-page-checkout.php'},3000);
//return false;
}
else
{
$("#reg_message").slideUp();
$("#reg_message").slideDown().html(html);
}
}
}
);
Try putting your ajax into submitHandler of validation plugin
$("form").validate({
rules: {
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
}
},
submitHandler:function(form){
$.ajax({....})
}
});
When running into problems use debug:true
for instant solution use "required" https://jsfiddle.net/et7qcrye/
<input type="text" name="name" id="name" class="NewsLetter1" required/>

How can I validate if email exists

I am using the jQuery validation plugin and it works correctly , but I have a problem checking email. I receive true or false dependant on if email exists or not. However I don't know how to change the state of validation in the form, because I can't pass the validation.
email: {
required: true,
email: true,
remote: {
url: "checkEmail",
type: "get",
success: function(data){
if (data.msg == true) {
///Email avaliable////
console.log("OK");
} else {
/////Email taken///
console.log("NO");
}
}
},
},
Could anyone help me?
Considering that the ajax call returns true or false based on data , you can try the following code snippet of email rule and messages rule .
email: {
required: true,
email: true,
remote: {
url: "checkEmail",
type: "post",
data: {
email: function() {
return $('#formID :input[name="email"]').val();
}
}
}
},
messages: {
email: {
required: "Please enter your email address.",
email: "Please enter a valid email address.",
remote: jQuery.validator.format("{0} is already taken.")
}
}

How do I define the value of an input for a remote check of existing values (username)?

This is using jQuery 1.6.1 and Validate 1.8.1.
I have been banging my head against a wall because of this problem, and now I'm trying the other approach to try and solve this problem. I need to query the database for existing usernames so that someone signing up doesn't register the same one again.
HTML:
<form class="cmxform" action="register.php" method="post" name="signup" id="signup">
<ul>
<li>
<label for="username">Username: <em>*</em></label>
<input type="text" id="username" name="Username" size="20" class="required" placeholder="Username" />
</li>
</ul>
</form>
This time, I'm trying to use the remote function for the validate script:
$("#signup").validate( {
var username = $("#username").val();
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
},
},
submitHandler: function(form) {
form.submit();
}
});
The code in question that doesn't work is var username = = $("#uname").val();. Firebug gives the error missing : after property id.
I'm including the mentioned variable above inside validate() because I only want the value of the input after I've typed something into it, not upon loading of the page.
The other problem I've been running into is making the remote error message ONLY show up when a username already exists in the database. Unfortunately, it shows up whether dbquery.php comes back as true or false. If I try an existing username, it returns false, then I rewrite a new username that returns true, the message doesn't go away. Similarly, when I write a username and it returns true, I still get the remote error message.
What am I doing wrong?
As you can read How can I force jQuery Validate to check for duplicate username in database?
The solution is to use the remote property:
Example with remote:
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "get",
data: {
action: function () {
return "checkusername";
},
username: function() {
var username = $("#username").val();
return username;
}
}
}
}
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available" in your PHP file.
var username = $("#uname").val();
instead of
var username = = $("#uname").val();
You can't have = =, it's a syntax error.
Also, make sure you properly 'escape' $("#username").val().
If someone enters: myname&action=dosomethingelse I'd give it a fair change it will dosomethingelse.
New answer:
$("#signup").validate( {
var username = $("#username").val(); // -- this is wrong
rules: {
Username: {
required: true,
...
});
You can fix this the easy way by just not declaring the variable at all since you're only using it is one place, but that's no fun :D
The solution is a closure:
$("#signup").validate( (function () {
var username = $("#username").val();
return {
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
}
},
submitHandler: function(form) {
form.submit();
}
};
}()));
(I haven't tested it, there may be a typo or syntax error).
If you have no idea what this does or why, don't worry about it :D

Categories