1110
1110

Reputation: 6839

Dynamically added form ajax not work

I have a list of div's.
When I click on a button in a div I switch div content with partial view which contain form.
This is code that happens when I click on that button:

@Html.ActionLink("edit", "EditUserLanguage", "UserLanguage", new { userLanguageId = Model.UserLanguageId }, new { @class = "editButton" })
...
$(document).on('click', '.editButton', function (e) {
        $.ajax({
            url: this.href,
            cache: false,
            success: function (html) {                
                var id = $(e.target).closest("div").attr("id");
                $("#" + id).empty();
                $("#" + id).append(html);
            }
        });
        return false;
    });

Html (partial view) that I add has:

 @using (Html.BeginForm("UpdateUserLanguage", "UserLanguage", FormMethod.Post, new { id = "updateUserLanagegeForm" }))
                            {
    ...

This main view where is the list of div's and where I add this new partial view I have this code:

$(function () {
            $('#updateUserLanagegeForm').submit(function () {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {                        
                        alert("work");                        
                    }
                });
                return false;
            });
        }); //update

When I click on submit action method is invoked and I get new partial view returned but not via ajax.
I only get that partial view returned. alert("work"); is never called.
What could be the reason that this ajax call doesn't work?

Upvotes: 0

Views: 167

Answers (1)

SachinGutte
SachinGutte

Reputation: 7055

submit handler is not being attached to form as form gets loaded after dom ready. So change your code to -

$('body').on('submit','#updateUserLanagegeForm',(function () {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function (result) {                        
            alert("work");                        
        }
    });
    return false;
});

This will attach handler to form even if it is added dynamically.

Upvotes: 2

Related Questions