0

I AJAXified commenting system so when Post Comment button is clicked ajax call is made instead of the original form submission. Thanks to my other question .submit doesn't work if the bind object was refreshed by ajax this works now even if the submit button is refreshed.

Now I want to validate the form before submitting but I cannot make it work. The submitHandler option is not called even though the form is valid. The alert( "Valid: " + commentform.valid() ); is triggered and after the the original submit is performed not the ajax one.

The javascript to submit the form looks like

jQuery(document).ready(function($){
        $('#content_container').on("submit","#commentform",function(){
                var commentform=$('#commentform'); // find the comment form

                console.log('Post Comment button was clicked');     


var validator = $("#commentform").validate({ 
    onsubmit: false,
    rules: { 
        author: "required", 
        email: { required: true, email: true }, 
        url: { url: true    }, 
        comment: "required" 
    }, 
    messages: { 
        author: "Please enter your name",   
        email: { required: "Please enter an email address", 
        email: "Please enter a valid email address" }, 
        url: "Please enter a valid URL e.g. http://www.mysite.com", 
        comment: "Please include your comment" 
    } ,

    submitHandler: function(form) {  // The jQuery.validate plugin will invoke the submit handler if the validation has passed.
            alert( "Valid (submitHandler): " + form.valid() );
            console.log("before exit");
            return;
            console.log("after exit");
        },
    invalidHandler: function(event, validator) {
            alert( "Valid (invalidHandler): " + form.valid() );
            console.log("before exit");
            return;
            console.log("after exit");
        }
});
alert( "Valid: " + commentform.valid() );
return;

        $.ajax({
            type: 'post',
            url: formurl,
            data: formdata,

Could someone suggest how to make the ajax call to submit form after the validation?

Community
  • 1
  • 1
Radek
  • 13,813
  • 52
  • 161
  • 255
  • 1
    Get rid of your `.on('submit')` handler. It's not needed since the plugin captures and handles the submit event with its `submitHandler` function. – Sparky Oct 15 '13 at 02:04
  • @Sparky: perfect it works but if I refresh the page via ajax clicking the "Post Comment" button doesn't trigger the validation but original submit. I need somehow to preserve the link to the form `$("#commentform").validate({ `even though the object is refreshed via ajax. That's what was addressed in my other question http://stackoverflow.com/questions/19343052/submit-doesnt-work-if-the-bind-object-was-refreshed-by-ajax – Radek Oct 15 '13 at 02:52
  • Your comment doesn't make sense to me. If you're using Ajax, then there wouldn't be a page refresh. – Sparky Oct 15 '13 at 03:03
  • OK it might make more sense if you read the other question. I have a page where I refresh the content ( the submit form included ) on ajax call. When I get rid of the whole line `$('#content_container').on("submit","#commentform",function(){` the validation works the first time the page is loaded. Then I load new html for `#content_container` where the form sits and then if I click submit form button the validation is not triggered. – Radek Oct 15 '13 at 03:07
  • Please be aware of the tags you're using and their descriptions. The [tag:validator] tag has nothing to do with this question. It's meant for "code validation tools". Edited. Thanks. – Sparky Oct 16 '13 at 16:31
  • Please show the rendered HTML markup so I can make a working demo. – Sparky Oct 17 '13 at 03:23
  • Is this good enough? http://pastebin.com/KTQ6sgPm not sure how I can simply it. I copied the whole body part. The thing is that the fist time page is loaded your approach works then after ajax call the whole `content_container` is refreshed and after that the ajax way of submitting form doesn't work. Let me know if you need something else. – Radek Oct 17 '13 at 05:32
  • I'm looking at it now, but it's preferred that your question be fully "self-contained", **not** rely on external links, other questions/answers, links in comments, etc. That your OP contain enough code to construct a concise demo of the problem. Looks like your jQuery is abruptly cut off as well. – Sparky Oct 17 '13 at 22:41

1 Answers1

0

In this case, you could try this:

    jQuery(document).ready(function($){
         $('#content_container').on("submit","#commentform",function(){
             var commentform=$('#commentform'); // find the comment form

             console.log('Post Comment button was clicked');     


     var validator = $("#commentform").validate({ 
        onsubmit: false,
        rules: { 
            author: "required", 
            email: { required: true, email: true }, 
            url: { url: true    }, 
            comment: "required" 
        }, 
        messages: { 
            author: "Please enter your name",   
            email: { required: "Please enter an email address", 
            email: "Please enter a valid email address" }, 
            url: "Please enter a valid URL e.g. http://www.mysite.com", 
            comment: "Please include your comment" 
        } 
    });
    if (commentform.valid()){
        //Your ajax to post the form
        $.ajax({
                type: 'post',
                url: formurl,
                data: formdata,
    }
    else{
       //form is not valid.
    }
    return false;// stop the form submission and refresh the page.
  });

});

You don't need the submitHandler and invalidHandler if you validate the form manually to send an ajax request.

This works but I recommend you to think about your current design to see if it's possible to avoid removing old forms with new forms and has to rebind the .validate() again everytime.

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • I tried that before I posted my question but I didn't use `return false` only `return` that's why it didn't work. Could you please explain the difference? Thank you – Radek Oct 15 '13 at 06:16
  • @Radek: browsers check the return value of your handlers. If the return value is false, browsers will stop default behavior of your element (in your case is form submission) and stop event propagation. `return;` is a different scenario, when calling this, you just exit the current function but does not return any value. – Khanh TO Oct 15 '13 at 06:25
  • So only `return;` just exits the current function but does not return any value means to continue with standard form submission? – Radek Oct 15 '13 at 06:29
  • 1
    @Radek: `return;` exits the current function returns `undefined` (no value) to the calling function. It's a problem because `false` and `undefined` are different. yes, the browser would submit the form. – Khanh TO Oct 15 '13 at 06:36
  • Perfect, thank you so much for the explanation. All clear now. – Radek Oct 15 '13 at 06:41
  • -1 for saying, _"You don't need the `submitHandler` and `invalidHandler` if you validate the form manually to send an ajax request."_ ~ Those are built-in event handler functions... there's no good reason not to use them. Adding yet another submit handler by enclosing `.validate()` inside an `.on('submit')` is redundant & superfluous. You should note that `.validate()` is the initialization method of the plugin, not the testing method, so you do not need to call it every single time the submit button is clicked. – Sparky Oct 16 '13 at 16:28
  • @Sparky: but the validation didn't work if `.on` was not used. I would be very happy to use 'better/more efficient' solution but I could not make it work otherwise. I am happy to try what you suggest, could you make an answer out of it? – Radek Oct 17 '13 at 00:20
  • @Radek, I'll revisit this tomorrow and make another answer as you requested. – Sparky Oct 17 '13 at 01:00
  • @sparky: thank you, did you understand my explanation why the solution you suggested didn't work? I am not 100% sure if I am right there but from the other question of mine I understood that if the
    that contains the form is reloaded via ajax the initialization for validation is lost. That's why I need to use .on This is what I understood maybe Khann can correct me if I am not right here.
    – Radek Oct 17 '13 at 01:34
  • @Sparky: because he is loading the forms using ajax. Everytime the forms are reloaded, all registered handlers (and configurations) using `.validate()` are gone. You have no way but to call the function again. That's problematic, I agree. I also recommended to think about the current design to avoid that. – Khanh TO Oct 18 '13 at 02:30
  • @Sparky: I also would to know if it's possible to use `.validate()` similarly to delegated event handlers. Thanks – Khanh TO Oct 18 '13 at 02:48
  • @Khanh, no, `.validate()` cannot be delegated like an event. – Sparky Oct 18 '13 at 03:09