Camilo Terevinto Camilo Terevinto - 1 month ago 7
Ajax Question

Document events unloaded upon replacing content

I am trying to add a loading animation to present to users while the application performs some long operations, currently testing with the login screen.

To render the returned HTML from the actions, I am using the code from a post that shows how to use

IRazorViewEngine
and
ITempDataProvider
to render views to string. I am also using some code found in different sites to handle the loading animation when the AJAX request starts/ends:

//inside form:
<button type="button" id="btnLogin" class="btn btn-default">
//below form:
@section Scripts{
<script type="text/javascript">
$(function ()
{
$body = $("body");

$(document).on({
ajaxStart: function () { $body.addClass("loading"); },
ajaxStop: function () { $body.removeClass("loading"); }
});

$("#btnLogin").on("click", function (e)
{
var form = $("#loginForm");
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data)
{
$("#myDIV").html(data.viewResult);
}
});
});
});
</script>
}


myDiv
is a simple div element that wraps the entire view. All works great, but when trying to perform the second AJAX request (because login failed due to invalid credentials) after all the div was replaced, the button does nothing.
What do I have to modify in the jQuery code to make this work? Do I have to put the view inside a partial view and put the code as part of the parent and make the child host the form?

Answer

You're replacing the button, so you have to use delegated event handlers

$(function() {
    $body = $("body");

    $(document).on({
        ajaxStart: function() {
            $body.addClass("loading");
        },
        ajaxStop: function() {
            $body.removeClass("loading");
        }
    });

    $("#myDIV").on("click", "#btnLogin",  function(e) {
        var form = $("#loginForm");
        $.ajax({
            type: "POST",
            url: form.attr('action'),
            data: form.serialize(),
            success: function(data) {
                $("#myDIV").html(data.viewResult);
            }
        });
    });
});