0

I have 3 partial views with JS using JQuery in each to post a form and open a new partial view when the form is posted.

What I am finding is that the first time the JS fires it works fine but if I then go to post the form on the new page, I calls the function from the previous page.

The code:

    $('#selector').click(function (e) {
    var actionName = $(this).attr("id")
    e.preventDefault();
    e.stopImmediatePropagation();
    alert("page1 js being called")
    $('#page1Form').submit(function () {
        $.ajax({
            url: 'Dashboard/Page1/',
            data: $(this).serialize(),
            type: 'POST',
            success: function () {
                $.ajax({
                    url: 'Dashboard/LoadPartial',
                    data: { viewName: actionName },
                    type: 'GET',
                    success: function (d) {
                        $('#partial').html(d);
                    }
                });
            },
        });
    });
    $('#page1Form').submit();
});

The second partial view has a function the same as that but only with the relevant selectors etc and for some reason the previous pages JS is being called as the alert alert("page1 js being called") is appearing in the browser!

Thanks in advance.

3

1 Answer 1

1

If you're loading partial views that means the entire page isn't being refreshed, and as a result the already loaded scripts will still be there. You'll need to remove the event handlers that correspond to the page1 content before adding the new content in:

$.ajax({
    url: 'Dashboard/LoadPartial',
    data: {
        viewName: actionName
    },
    type: 'GET',
    success: function (d) {
        $('#selector').off('click'); // remove the click event handler
        $('#page1Form').off('submit'); // remove the submit event handler
        $('#partial').html(d); // add your new content
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

And evaluate the ajaxed javascript somehow so it will be executable.
So #selector.click() normally just is a navigation link, but in these pages it is changed so that the form can be submitted and then navigation takes place. However if im in a view where the #selector.click() should just behave as normal, it still tries to perform the function of the last post and navigate page. I have done .off on the click handler as above but doesnt seem to affect outside of these 3 post form and navigate pages

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.