I am trying to submit the form using jquery validate and ajax.But it doesnt work.neither it throws any error.
here is the html
{% if form %}
<form method="POST" action="." id="change_password_form">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="action" value="{% trans 'change password' %}"/>
</form>
{% else %}
<p>{% trans 'Your password is now changed.' %}</p>
{% endif %}
Here is the script
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
$("#change_password_form").validate({
rules: {
password1: {
required: true,
maxlength:10
},
password2: {
required: true,
maxlength:10
},
},
messages: {
password1: {
required: "Please provide a password",
},
password2: {
required: "Please Confirm your password",
},
},
submitHandler: function(form) {
var pass = $('input[name=password1]').val();
var repass = $('input[name=password2]').val();
if (pass != repass) {
console.log("error")
}
else {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
})
.done(function (response) {
$('#loading-image').hide();
if (response.location == 'accounts/password/reset/key/done/'){
window.location = "{% url 'home' %}"
}
}).error(function(response){
console.log(response)
});
return false;
}
});
});
</script>
Somehow the submit event is not occurring ? what can i do to submit the form using ajax and jquery validate
I did some minor changes in your code, i think you had a typo.
The problem was you was using the rules without "" and jquery.validate was not able to recognize.
I also added a custom validation to control if the passwords are the same, all validations should be with standard rules or customs but you shouldn't add validations into submitHandler method.
$("#change_password_form").validate({
rules: {
"password1": {
required: true,
maxlength:10,
"isSamePassword": true
},
"password2": {
required: true,
maxlength:10,
"isSamePassword": true
}
},
messages: {
"password1": {
required: "Please provide a password",
maxlength:"Max 10",
isSamePassword: "Pwd no son iguales"
},
"password2": {
required: "Please provide a password",
maxlength:"Max 10",
isSamePassword: "Pwd no son iguales"
}
},
submitHandler: function(form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
})
.done(function (response) {
$('#loading-image').hide();
if (response.location == 'accounts/password/reset/key/done/'){
window.location = "{% url 'home' %}"
}
}).error(function(response){
console.log(response)
});
}
});
$.validator.addMethod("isSamePassword", function(value) {
var pass = $('input[name=password1]').val();
var repass = $('input[name=password2]').val();
return pass === repass;
}, 'Pwd no son iguales');
Related
<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
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){
}
});
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/>
I couldn't find the mistake but it submit form twice . Please help me what i missed in this .
$('#supplierForm').on('submit', function(e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
async: false,
data: $("#supplierForm").serialize(),
url: '{{ url('supplier_edit_new') }}',
type: 'POST',
success: function (data) {
window.location.reload();
}
});
}
return false;
})
;
For validating script
$("document").ready(function(){
$('#supplierForm').validate({
errorClass: 'help-block',
rules: {
'line1': "required",
'line2': "required",
'suburb': "required",
'state' : "required",
'country':"required",
},
messages: {
'line1':{required: "Please enter supplier's address."},
'line2':{required: "Please enter supplier's address."},
'suburb':{required: "Please enter supplier's suburb."},
'state':{required: "Please select a state"},
'country':{required: "Please enter country"},
'postcode':{required: "Please enter postcode"},
},
highlight: function (element) {
$(element).parent().parent().removeClass("success").addClass("error");
},
unhighlight: function (element) {
$(element).parent().parent().removeClass("error").addClass("success");
}
}); // validate
});
For html
{{ form_widget(form.submit,{'attr':{'class':'btn btn-primary btn-large btn-style','value':'Save changes'} }) }}
it generate
<button id="ovc_bundle_productbundle_supplier_submit" class="btn btn-primary btn-large btn-style" value="Save changes" name="ovc_bundle_productbundle_supplier[submit]" type="submit">Save / Update Details</button>
Try this to prevent binding the event multiple times,
$('#supplierForm').off('submit');
$('#supplierForm').on('submit', function(e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
async: false,
data: $("#supplierForm").serialize(),
url: '{{ url('supplier_edit_new') }}',
type: 'POST',
success: function (data) {
window.location.reload();
}
});
}
return false;
})
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