Question

I am trying to use ajaxForm on my on-the-fly created form. In fact, my application will produce a link 'on the fly' and by clicking on that link, it will produce an ajaxForm (again on-the-fly by jQuery!), so I used the .live() function with ajaxForm(). This is my wrong code:

$('form').live('submit', function() {
    $(this).ajaxForm({dataType: 'html', success: function(data) {
        alert(data);
    }});
    return false; // For preventing page refresh!
});

In my form, when I click the submit button, the page refreshes.

Is there a solution?

Was it helpful?

Solution

As others have said, your return false should work.

So, something else is wrong. Ensure that jQuery is loaded properly and that your on-submit handler actually executes by placing debugging code in it.

Also, make sure that you have Firebug installed and enabled (or equivalent for your browser) so that you can perform your debugging.

OTHER TIPS

Try using event.stopPropagation(); which is a JQuery function.

To do so you will need to take the event object as parameter to the handeler:

$('form').live('submit', function(event){

and use this line in place of return false; :

event.stopPropagation();

The return false should work, but, it's best practice to either do event.preventDefault() or event.stopPropagation() when you have no need to do both. In this case it would be event.preventDefault() because you want to stop the default action of submitting the form. But like i said return false; should have worked in your case so i'm suspecting you might be getting some kind of errors with the plugin you're using. If i were you i would look at the documentation again for your plugin and make sure your options are correct. Right off the back i see a dataType: 'html' and there can only be 'xml', 'script', or 'json' as stated in the documentation...You may want to have another look at your usage of the plugin.

You might need to call preventDefault in place of "return false". Pseudo code of that use case of jQuery livewith form combined with AJAX is below:

    //Override form submit
    $("form").live("submit", function (event) {
        event.preventDefault();
        var form = $(this);
        $.ajax({
            url: form.attr('action'), // Get the action URL to send AJAX to
            type: "POST",
            data: form.serialize(), // get all form variables
            success: function(result){
                // ... do your AJAX post result
            }
        });
    });

Also, I am not sure if with ajaxForm (as I haven't used ajaxForm) you need to use jQuery.live. Inferring from the doc, you might not need it at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top