I want to validate a form with the jQuery form validation plugin but I was not able to send a custom Ajax request with the validation handler:
$('#headForm').validate(
{
//submitHandler: submit,
errorClass: "invalid",
rules: {
title: {maxlength: 50}
},
messages: {
title: {maxlength: 'Max 50 chars'}
}
});
My orginal submit handler looked like this:
$('#headForm').submit(function(event)
{
event.preventDefault();
$.ajax(
{
type: "PUT",
url: "/target",
data: $('#headForm').serialize(),
dataType: "json",
success: function()
{
alert("ok");
}
});
});
I tried to move it to a usual function and register it as a submitHandler in the validation block, but it didn't work.
function submit() { // impossible to pass the event!
$.ajax( ...
}
How can I combine jQuery validation with a custom Ajax request?
Possible form validation bug:
I've removed the validation code to see whether the submission works without it. And it did not unless I removed the link to jQuery form validation library! So it seems like validation is breaking jQuery core. Have I already said that I love dynamic typing ... ;-)
Did you define a parameter in the submit() function?
(I'm guessing that you didn't, and that could be why it didn't work)
I think you just need to specify the 'form' parameter, and then call serialize() on that parameter, as follows:
submitHandler: function(form) {
$.ajax({
type: "PUT",
url: "/target",
data: form.serialize(),
dataType: "json",
success: function()
{
alert('ok');
}
});
}
See the docs: http://docs.jquery.com/Plugins/Validation/validate#options
Related
I have always used query ajax request to something simple like preventdefault form submit and adding beforesend function or complete function after the form is submitted like this to my nodejs backend:
$.ajax({
type: "POST",
url: "/contact",
beforeSend:function(){
$(".loading_msg").hide();
},
complete:function(){
$(".loading_msg").show();
setTimeout(function(){
console.log('Here')
$(".loading_msg").fadeOut("slow");
$("#message").val("")
},3000)
}
});
Now, I have a sitution where I have to submit only part of the form input elements. There are also input elements inside the form which is dynamically generated.
Is there a way for me to send only input boxes with id's or classes that I want rather than the entire form?
If you want to send some particular data to your server, you can config the data by yourself like the following:
$.ajax({
type: "POST",
url: "/contact",
data: {
myKey1: $("#myKey1").val(),
myKey2: $("#myKey2").val()
},
beforeSend:function(){
$(".loading_msg").hide();
},
complete:function(){
$(".loading_msg").show();
setTimeout(function(){
console.log('Here')
$(".loading_msg").fadeOut("slow");
$("#message").val("")
},3000)
}
});
I am using asp.net MVC 5 and trying to validate form on submission. everything works fine until i added the below line of code to validate form using ajax call.
$('#signupform').validate({
submitHandler: function (form) {
$.ajax({
type: 'POST',
data: JSON.stringify({ type: "WhatsNew", code: $('#PrimaryCode').val() }),
url: '#Url.Action("CheckCode", "Home")',
dataType: 'json',
contentType: 'application/json'
})
.done(function (response) {
if (response == 'success') {
alert('success');
}
else {
alert('failed');
}
});
return false; // required to block normal submit since you used ajax
}
});
the above code simply blocking the submission of form.
You prevented submission by return false; in order to ajax-validate the form, but the form is not submitted after successful validation.
Add a form submit trigger inside .done();
if (response == 'success') {
// since validation is success, submit form here (e.g. YourForm.submit())
}
Possible walk through:
Before submitting the form inside .done(); make sure you remove/unbind validate from you form.
Follow this link: click here for another couple of ways.
I want to use form validation methods of CI for validating my input data. As the form submitted via AJAX I'm using serializeArray() to post data to my controller so I don't have to post on by one data or wrinting some each() function. The problem is that form validation look for data in $_POST. Using serialize() didn't help neither. Is there any solution beside extending form validation library?
here my code:
(controller)
$form_data = $this->input->post('form_data');
$this->load->library('form_validation');
$this->form_validation->set_rules('p_company_name', 'نام شرکت', 'required');
if ($this->form_validation->run() == FALSE)
{
echo "fail";die(); // if i use serialize() or serializeArray()
}
else
{
echo "success";die(); // if i use label:value for each form input
}
js code:
$.ajax({
type: "POST",
cache: false,
url: url,
data: {'form_data': form_data},
dataType: "html",
success: function(res, textStatus, xhr)
{
// do something
},
error: function(xhr, textStatus, thrownError)
{
//do something else
},
complete: function()
{
// do some final thing
},
async: true
});
Thanks in advance
post your data as:
data: form.serialize(),
and it will work as normal (form being a normal jquery reference to your page form, not just the word "form")
I have an form loaded by AJAX, and inside that form I have render the reCaptcha control.
When I post the form, first I validate, and that use my webservice to validate the captcha. If it all data is right I want to post the form.
But the last behavior don't append...
I read this posts:
Can't submit after preventDefault
How to reenable event.preventDefault?
Re-enabling Submit after prevent default
jQuery: call the action's form after calling preventDefault()
But none of the solutions work... :(
My code:
$('#myForm').submit(function (e) {
e.preventDefault();
var captchaInfo = {
challengeValue: Recaptcha.get_challenge(),
responseValue: Recaptcha.get_response(),
};
$.ajax({
type: 'POST',
url: '#Url.Action("ValidateCaptcha")',
data: JSON.stringify(captchaInfo),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
if (msg) {
$('#myForm').submit();
}
else {
helpers.setCaptcha("captcha");
}
},
error: function (req, status, error) {
alert("error: " + error);
helpers.setCaptcha("captcha");
},
});
});
How I resolve this?
Thanks in advance
When you call .submit() the same code will be called (ending up in possibly an infinite loop). Try restructuring and passing a value to the .submit() call, like this:
$('#myForm').submit(function (e, passThrough) { // <-- DECLARE HERE!!
if (passThrough) { // <-- CHECK HERE!!
e.preventDefault();
var captchaInfo = {
challengeValue: Recaptcha.get_challenge(),
responseValue: Recaptcha.get_response(),
};
$.ajax({
type: 'POST',
url: '#Url.Action("ValidateCaptcha")',
data: JSON.stringify(captchaInfo),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
if (msg) {
$('#myForm').trigger("submit", [true]); // <-- PASS HERE!!
}
else {
helpers.setCaptcha("captcha");
}
},
error: function (req, status, error) {
alert("error: " + error);
helpers.setCaptcha("captcha");
},
});
}
});
The value passed (true), is available in the handler's parameters. So just check for that. If it's true, you know it was manually called and shouldn't validate the captcha, basically passing through the handler and allowing the default behavior.
Reference:
.trigger(): http://api.jquery.com/trigger/
Try removing the submit handler if it validates.
$('#myForm').off('submit');
Trigger the event on the form node itself.
$('#myForm')[0].submit()
this will cause it to bypass the jQuery bound event.
I have the following AJAX function with JQuery:
var formData = $('#FonykerEditForm').serialize();
$.ajax ({
type: 'POST',
url: '<?php echo $html->url('/fonykers/edit',true); ?>',
data: formData,
dataType: 'json',
success: function(response) {
message.html(response.msg);
message.fadeIn();
if(!response.ok) {
message.removeClass('success');
message.addClass('error');
} else {
message.removeClass('error');
message.addClass('success');
username = $('#FonykerUsername').val();
email = $('#FonykerEmail').val();
}
$('#save-account-button').removeAttr('disabled');
$('.input-text').removeClass('ok');
$('.input-combo').removeClass('ok');
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
$('#save-account-button').removeAttr('disabled');
}
});
The problem I'm having is that a type file field in my form is not getting submitted along with the rest of the data of the form, how can I include the file in the data of the ajax request?
I tried this link and this works fine for me.
http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/
Example:
$( '#my-form' ).submit( function( e ) {
$.ajax( {
url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
} );
Like I said in the comment above, sending files via ajax is not straightforward. If you wish to try it anyway. The normal approach I've seen is to create a new iframe, add a file input field to it, select your file and submit it programmatically. This way, the iframe does the submission in the background.
Take a look at how this plugin does it:
https://github.com/valums/file-uploader/blob/master/client/fileuploader.js#L995
https://github.com/FineUploader/fine-uploader
Basically an AJAX will submit data in the form of key/value pairs.. Since files are binary data, you can't submit files using Ajax.. You'll need to submit the data using a standard form submit instead and on the server since accept a form/multipart