Javascript loading after ajax loading

After returning to main content with ajax load, the function onload

didn't run. I can understand why, but how can I make it work in this state?

<script type="text/javascript">
        onload = function() {
            if (!document.getElementsByTagName || !document.createTextNode) return;
            var rows = document.getElementById('chat').getElementsByTagName('tr');
            for (i = 0; i < rows.length; i++) {
                rows[i].onclick = function() {
                    $("#chat_main").load("chat", {
                       m: this.id,
                       ajax: 1 //here we are loading another page
                   });
                }
            }
        }
    </script>
    <script>
        function return_to_main() {
            $("#chat_main").load("chat", {
                ajax: 1 //here we trying to load back main page
            });
        }
    </script>

      

PS is return_to_main()

tied toinput type="button"

+3


source to share


2 answers


Call your function after request:

$("#chat_main").load("chat", {
    ajax: 1 //here we trying to load back main page
}).done(onload); // <--

      



If .load

not using a promise:

$("#chat_main").load("chat", {
    ajax: 1 //here we trying to load back main page
}, onload); // <--

      

0


source


You are binding on the window.onload call. It is not magically called every time the page content is refreshed. It is called only once. You must call the function every time you want the code to work. So when the Ajax call is complete, you should have called it.

BUT you are using jQuery, so use it.



There is no reason why you would need to bind to every row of the table. Use event delegation. Now that the content changes, you will still be linked to events.

$( function () {  //document ready
    var chatMain = $("#chat_main");
    chatMain.on("click", "table tbody tr", function () {  //listen for clicks on table row
        chatMain.load("chat",
            {
                m: this.id,
                ajax: 1 //here we are loading another page
            }
        );
    });
});

      

+1


source







All Articles