Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS MVC form AJAXifying techniques [closed]

I'm looking for most elegant way to ajaxify my forms (with jQuery).
How do you do this?

like image 599
Arnis Lapsa Avatar asked May 30 '09 16:05

Arnis Lapsa


1 Answers

Here is my solution (I think it is a Progressive enhancement solution), using only jQuery without any plugins:

var form = $('form#YourFormId');
$(':submit', form).click(function (event) {
    event.preventDefault();
    $.post(form.attr('action'), form.serialize(),
        function(data, status) {
            if(status == 'success') {
                // your code here
            }
        }
    );
});

UPDATED:

If your POST response is "HTML with form" then try this:

function ajaxifyForm(form) {
    $(':submit', form).click(function (event) {
        event.preventDefault();
        $.post(form.attr('action'), form.serialize(),
            function(data, status) {
                if(status == 'success') {
                    var newForm = $(data);
                    ajaxifyForm(newForm);
                    form.after(newForm).remove();
                }
            }
        );
    });
}
like image 190
eu-ge-ne Avatar answered Sep 21 '22 11:09

eu-ge-ne