Document.Ready() is not working after PostBack
Asked Answered
B

9

39

I have a page that contains a user control within an update panel. $(document).ready(function() ) { is called and executes the code correctly when the page firsts loads but if the user clicks a button (within the user control), the document.ready() doesn't get called (document.load, onload also don't work)

I have researched this on the net and found similar problems but nothing that can explain why this isn't working. What other causes can there be for document.ready not working?

Baneful answered 6/3, 2012 at 15:40 Comment(2)
This could be several things. Have any code to share?Broomrape
Xyan is right, I found a different dev had added a clause which checked the url path but the casing on the url was being ignore, my code wasn't being reached. I recommend adding alerts to your JS to ensure its not being called and work from there.Marci
L
53

This will be a problem with partial postback. The DOM isn't reloaded and so the document ready function won't be hit again. You need to assign a partial postback handler in JavaScript like so...

function doSomething() {
   //whatever you want to do on partial postback
}

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(doSomething);

The above call to add_endRequest should be placed in the JavaScript which is executed when the page first loads.

Landy answered 6/3, 2012 at 15:43 Comment(10)
It should be Sys.WebForms.PageRequestManager.getInstance().add_endRequest(doSomething);Dicentra
Is the 'Sys.WebForms.PageRequestManager' C# or javascript?Baneful
It's Javascript - it's a routine of the Microsoft Ajax JS libraries which are loadedLandy
@aspdotnetuser Sorry - that's because I'd put doSomething() as the argument to add_endRequest - I believe that add_endRequest only accepts a single function reference as argument. Obviously putting doSomething() as the argument would pass the return value of doSomething to add_endRequest...Landy
This is not working. Where should I need to put this?Carbonado
@Carbonado It needs to go in JavaScript which is executed when the page first loadsLandy
@ElRonnoco I'm working on an asp.net MVC application. Should I put this on root template?Carbonado
@Carbonado - I'm not sure about that, I don't do MVC I'm afraid. I don't even know if you will have Sys.WebForms.PageRequestManager in an MVC project. Your issues sounds like it could be completely different. I would advise posting a new question.Landy
@ElRonnoco Thanks for your response. I already posted it here.. #23453749Carbonado
BeginRequest worked for me instead: window.Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(**Javascript function here **)Speciation
I
31

Instead of $(document).ready you could use function pageLoad(){}.

It's automatically called by the ScriptManager on a page, even on a postback.

Irma answered 6/3, 2012 at 15:45 Comment(3)
function pageLoad() doesn't appear to do anything.Baneful
and you have an <asp:ScriptManager runat="server" /> on the page?Irma
Yes, the page has a ScriptManagerBaneful
W
17

I've run into this a while ago, as El Ronnoco said, it has to go with the DOM not being reloaded. However you can simply change $(document).ready(function() { to

Sys.Application.add_load(function() {

This will force it to run on every postback.

You can use function pageLoad() as well, but you can only have one pageLoad function, whereas with Sys.Application.add_load, you can add as many handlers as you wish.

Westney answered 10/5, 2012 at 20:48 Comment(2)
Hi dcreight, in the page add the following: <asp:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <asp:ScriptReference Path="~/path/to/file.js" /> </Scripts> </asp:ScriptManager> Then in the external file (file.js), do the following: Sys.Application.add_load(function() { //insert code here to do on every postback }); The problem with using the function pageLoad() {} approach is that you can only have one of these in a page, vs my approach above you can add as many add_load functions as you want. If you still have trouble please send the error or sample code.Westney
Thank you very much! Needed it for jQueryUI Accordion in an UpdatePanel. Was trying for hours until I found this.Flub
B
10

Bestest way is

<asp:UpdatePanel...
<ContentTemplate
     <script type="text/javascript">
                    Sys.Application.add_load(LoadScript);
     </script>
 you hemla code gose here 
</ContentTemplate>
    </asp:UpdatePanel>

Javascript function

<script type="text/javascript">

        function LoadScript() {
            $(document).ready(function() {

                   //you code gose here 
                                    });
         }
</script>

or

Its under UpdatePanel than you need to register client script again using

ScriptManager.RegisterClientScript

or

$(document).ready(function() {
    // bind your jQuery events here initially
});

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(function() {
    // re-bind your jQuery events here
    loadscript();

});


$(document).ready(loadscript);

function loadscript()
{
  //yourcode 
}
Bibliophile answered 6/3, 2012 at 15:43 Comment(2)
Do you mean register the javascript I want to excutue again?Baneful
@aspdotnetuser - yes liket that or as suggested in below answer you can do it easilyBibliophile
D
3

This is an example that worked for me in the past:

<script>
function MyFunction(){ 
    $("#id").text("TESTING");
}
//Calling MyFunction when document is ready (Page loaded first time)
$(document).ready(MyFunction); 

//Calling MyFunction when the page is doing postback (asp.net)
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(MyFunction);
</script>
Damon answered 2/6, 2016 at 20:18 Comment(0)
I
2

This code below works nice to solve this problem. As indicated in link posted before (http://encosia.com/document-ready-and-pageload-are-not-the-same/), when you have an asp.NET with updatePanels you shall use function pageLoad(). When you have only one page and in each postback it will be fully reloaded, the $(document).ready() is the right option.

Example using pageLoad:

    function pageLoad() {

        $(".alteraSoVirgula").keyup(function () {
            code here
        })
    }
Inapposite answered 30/8, 2016 at 16:56 Comment(2)
Your answer does touch on some of the same ideas as the other answers that have been submitted(and the accepted answer) but it contains a lot of extra fluff that is specific to wherever you originally wrote this code. To get more positive feedback on your answer I would suggest removing anything that is not specific to the question being asked and add an explanation as to why your solution fixes the problem.Abeokuta
Yes, very nice job.Abeokuta
D
0

I was also facing the same problem but i found the jQuery $(document).ready event handler works when page loads, but after ASP.Net AJAX UpdatePanel Partial PostBack it does not get called. so use Sys.Application.add_load(function(){}); instead of $(document).ready. This works perfectly for me :)

<script>
Sys.Application.add_load(function() { //Your code }); </script>

Dividers answered 7/7, 2016 at 6:7 Comment(0)
S
0
$(document).ready(function () {
    PreRoles();
});

//On UpdatePanel Refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
    prm.add_endRequest(function (sender, e) {
        if (sender._postBackSettings.panelsToUpdate != null) {
            PreRoles();
        }
    });
};

function PreRoles() {
    // Add codes that should be called on postback
}
Spillar answered 23/1, 2021 at 15:31 Comment(0)
C
-2

Most of the times, this is happening because of the Updatepanle. Just put postback triggers to the button and it will solve this.

Cybernetics answered 9/11, 2014 at 11:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.