Jquery Validation Plugin, dynamic form validation - jquery-validate

I'm using the Jquery Validation Plugin to forms loaded via Ajax (dynamic forms). I know that as of Jquery 1.4, live events on submit is now possible. Now the problem is I want to show a confirm message after the dynamic form has been validated. My code looks like this:
$('.dynamicForm').live('submit',function(){
$(this).validate();
if($(this).valid()){
if(!confirm('Are you sure?'))
e.preventDefault();
}
});
It's not working as expected. Somehow confirmation shows first, then at the second time I submit the form, that's the time the validation happens. Any ideas?

Somehow this seems to work:
$('.dynamicForm').live('mouseover',function(){
$(this).validate({
submitHandler:function(form){
if(confirm("Are you sure?")){
form.submit();
}
}
});
});

Use the submitHandler function available in the validate options:
$(".dynamicForm").validate({
submitHandler: function(form) { //Only runs when valid
if(confirm('Are you sure?'))
form.submit();
}
})
From the docs - submitHandler:
Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.

Related

form submission using ajax-jquery and stopping the normal html submission

i am working on a html form where i am using a jquery ajax function that is called in the tag with onSubmit but the problem is that when user presses submit button or enter, the form gets submitted and page gets refreshed and the ajax function is not executed resulting in an output that is undesired.
How can i stop the normal submission and make the form submission only using ajax function and why the ajax function is not getting executed..i even tried .submit attribute of jquery but nithing happened.
please suggest some hacks/methods to deal with it. thanks
You can prevent the default behaviour of the submit event by using
$( "#target" ).submit(function( event ) {
event.preventDefault();
});
This could be find in the JQuery documentation https://api.jquery.com/submit/
To disable form submission change your code to following:
<form action="/" method="POST" onSubmit="return comment();">
...
</form>
function comment() {
...
return false;
}
Working sample is here https://jsfiddle.net/gevorgha/5dyc2ye9/ , try changing return false; to return true; and you will see submission.

How do I bind a success behaviour to another ajax form submission?

Similar to this question, I'm wanting to run a function when an ajax form is successfully submitted, but I don't have direct access to the initial ajax code that loads the form.
How would I check that the form was successful given that I can't add code to the initial ajax success call?
$('#registration-form').submit( function() {
alert('registered successfully');
});
try binding .ajaxSuccess() to your element http://api.jquery.com/ajaxSuccess/
$('#registration-form').ajaxSuccess(function() {
alert('registered successfully');
});
Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.
You could try to use the ajaxSucess() global ajax event handler:
$(document).ajaxSuccess(function() {
alert('registered successfully');
});

Magento ajax form validation

I have a form in Magento that I build in code, and that works with ajax, which I need to validate.
I would like to be able to use Magento's built-in validation functionality, but I don't know how I would trigger it since the form is not submitted. The data is retrieved via ajax and outputted in a list below the form.
Is there someone who can point me in the right direction?
Thanks in advance.
Edit:
This is the javascript code used to hande the ajax request. Its called by the onclick event of the button.
function advancedtranslateSearch(url){
new Ajax.Request(url, {
method: 'get',
parameters: $('search_form').serialize(),
onSuccess: function(transport) {
json = transport.responseText.evalJSON();
$('result').update('<div class="hor-scroll">'+json.records+'</div>');
}
});
}
You should use form's onsubmit event.
To prevent page from reloading you must return false value from your function.

How to avoid redirect after form submission if you have a URL in your form's action?

I have a form that looks like this:
<form name="formi" method="post" action="http://domain.name/folder/UserSignUp?f=111222&postMethod=HTML&m=0&j=MAS2" style="display:none">
...
<button type="submit" class="moreinfo-send moreinfo-button" tabindex="1006">Subscribe</button>
In the script file I have this code segment where I submit the datas, while in a modal box I say thank you for the subscribers after they passed the validation.
function () {
$.ajax({
url: 'data/moreinfo.php',
data: $('#moreinfo-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#moreinfo-container .moreinfo-loading').fadeOut(200, function () {
$('form[name=formi]').submit();
$('#moreinfo-container .moreinfo-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
Unfortunately, after I submit the datas, I'm navigated to the domain given in the form's action. I tried to insert return false; in the code (first into the form tag, then into the js code) but then the datas were not inserted into the database. What do I need to do if I just want to post the data and stay on my site and give my own feedback.
I edited Eric Martin's SimpleModal Contact Form, so if more code would be necessary to solve my problem, you can check the original here: http://www.ericmmartin.com/projects/simplemodal-demos/ (Contact Form)
Usually returning false is enough to prevent form submission, so double check your code. It should be something like this
$('form[name="formi"]').submit(function() {
$.ajax(...); // do your ajax call here
return false; // this prevent form submission
});
Update
Here is the full answer to your comment
I tried this, but it didn't work. I need to submit the data in the succes part, no?
Maybe, it depends from your logic and your exact needs. Normally to do what you asking for I use the jQuery Form Plugin which handle this kind of behavior pretty well.
From your comment I see that you're not submitting the form itself with the $.ajax call, but you retrieve some kind of data from that call, isn't it? Then you have two choices here:
With plain jQuery (no form plugin)
$('form[name="formi"]').submit(function() {
$.ajax(...); // your existing ajax call
// this will post the form using ajax
$.post($(this).attr('action'), { /* pass here form data */ }, function(data) {
// here you have server response from form submission in data
})
// this prevent form submission
return false;
});
With form plugin it's the same, but you don't have to handle form data retrieval (the commented part above) and return false, because the plugin handle this for you. The code would be
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm(function() {
// this call back is executed when the form is submitted with success
$.ajax(...); // your existing ajax call
});
});
That's it. Keep in mind that with the above code your existing ajax call will be executed after the form submission. So if this is a problem for your needs, you should change the code above and use the alternative ajaxForm call which accepts an options object. So the above code could be rewritten as
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm({
beforeSubmit: function() { $.ajax(...); /* your existing ajax call */},
success: function(data) { /* handle form success here if you need that */ }
});
});

get $.post to work with the validate plugin on multiple forms without seperate functions

On a fansite im doing http://yamikowebs.com/ee/
I have a few forms (2 atm). I used $.post to find out what form is being submited. submit the form and display that pages results where the form was originally with .html().
My next step was to use the validator which is working fine but im not sure how to put the 2 together.
submitHandler: function(form){} seems to be the setting for how its submitted. However, I can't get this to work with my $.post function or find out what form is being processed.
If I leave the defaults for validation plug-in if there no errors it will send you to the page. the ajax plug-in that it works with doesn't do what I want. Below is my $.post function
form validation:
//ajax post
$("form").submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent("div")
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
http://docs.jquery.com/Plugins/validation#source is the validation plugin
You're correct in thinking that submitHandler is the right callback to use. However, I ran into some interesting issues while using it with multiple forms (like you're trying to do). For example, in this code:
$("#form1, #form2").validate({
submitHandler: function(form) {
alert(form.action);
alert(form.id);
}
});
The submitHandler callback does not get supplied the correct parameter (it always gets #form1). I believe this is actually a bug in jQuery-validate (so I've filed it here).
Anyway, a decent workaround would be to wrap the validate call in .each():
$("form").each(function() {
$(this).validate({
submitHandler: function(form) {
/* 'form' has the correct value */
var values = $(form).serialize(),
$div = $(form).parent("div");
alert(form.action);
alert(form.id);
/* Perform AJAX call here */
}
});
});
Example: http://jsfiddle.net/andrewwhitaker/MmCXN/

Resources