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.
Related
I try to submit a form using ajax. Here is my code:
$BTN.click(function () {
$.ajax({
type: 'POST',
url: "/Record/Edit",
contentType: 'application/json',
data: JSON.stringify(data),
dataType: "json",
});
});
It works well. But i want to put a validation message to some inputs where the inputs need to be filled. I used has-value in the class. It validates the value when the form is being submitted. So I used this code to submit form. $('#frmEditCPRRecord').on("submit", function (e) { }); It did validates my form, but doesnt submit it.
The login form on my site is shown using an overlay/modal with jquery-modal (http://kylefox.ca/jquery-modal/examples/)
I'm using ajax + php to validate the form. If validation passes, the form should be submitted.
I can halt the submit for validation (using return false), and the validation itself is working fine. But I don't know how to submit the form
I have tried many naive variations: return true, $theform.submit(), $("body").unbind("#myloginform") and more.. but so far no luck
$("body").on("submit", "#myloginform", function() {
$theform = $(this);
$.ajax({
url: "login_check.php",
type: "POST",
cache: false,
timeout: 9000,
data: $theform.serialize(),
dataType: "json",
success: function(data) {
if (data) {
if (data.status == "ok") {
alert("success! now the form can be submitted");
// SUBMIT THE FORM (instead of the alert)
} else {
$("body #loginstatus").html(data.status);
}
} else {
alert("Error bla bla.");
}
},
error: function(e) {
alert("Error (ajax) bla bla.");
}
});
return false;
});
To submit the FORM, you can call js native submit method:
document.getElementById('myloginform').submit();
See variants:
$('#myloginform')[0].submit();
$('#myloginform').get(0).submit();
An other way would be to set context option of ajax to this:
$.ajax({
context: this,
...,
});
And then in success callback, submit FORM using:
this.submit();
EDIT: i see you are already using a variable reference, so in your case, you can use too:
$theform[0].submit();
All these snippets won't trigger jQuery submit handler, avoiding a circular reference error.
Another approach:
var checkValid = false;
$("body").on("submit", "#myloginform", function () {
$theform = $(this);
if (!checkValid) {
$.ajax({
url: "login_check.php",
type: "POST",
cache: false,
timeout: 9000,
data: $theform.serialize(),
dataType: "json",
success: function (data) {
if (data) {
if (data.status == "ok") {
alert("success! now the form can be submitted");
// Everything is OK
checkValid = true;
$theform.submit();// Next time, no validation process, just natural send of the form.
} else {
$("body #loginstatus").html(data.status);
}
} else {
alert("Error bla bla.");
}
},
error: function (e) {
alert("Error (ajax) bla bla.");
}
});
return false;
}
});
Since you're using jQuery, I would suggest that you check out the jQuery submit function
http://api.jquery.com/submit/
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 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
I have a simple one text input form that when submitted, needs to fetch a php file (passing the inputs to the file) and then take the result (just a line of text) and place it in a div and fade that div into view.
Here is what I have now:
<form id=create method=POST action=create.php>
<input type=text name=url>
<input type="submit" value="Create" />
<div id=created></div>
What I need is the results of create.php?url=INPUT, to be dynamically loaded into the div called created.
I have the jquery form script, but I haven't been able to get it to work right. But I do have the library loaded (the file).
This code should do it. You don't need the Form plugin for something as simple as this:
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
This works also for file upload
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
$('#created').html(data); //content loads here
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
You must use AJAX to post the form if you don't want the page to be refreshed.
$('#create').submit(function () {
$.post('create.php', $('#create').serialize(), function (data, textStatus) {
$('#created').append(data);
});
return false;
});