0

I am trying to call a JavaScript function after load...like totally after the page loads. It's part of a chatroom I'm designing, in which a cron repeatedly checks for new data, and if there's new data, it tells the chatroom index.php that there's new data. The page then prints some javascript, but the page has already loaded. How do I call the functions and lines of execution after the page has loaded? Thanks so much in advance!

EDIT: Here's the code:

if($connection) {
    $sql = "SELECT * FROM `refresh` WHERE `refresh`=1;";
    $query = mysqli_query($connection, $sql);
    $result = mysqli_fetch_fields($query);
    if($result !== null) {
        ?>
        <script type="text/javascript">
            refreshChat();
            $.ajax({url: "chat.log", type: "POST"})
            .done(function (data) {
                $("#chattxt").html(data);
            });
        </script>           
<?php
                }
            }
//More code irrelevant to this problem.

The JavaScript function refreshChat() is simply the same code I put after the call to it. I have also tried heredoc, and it didn't work either.

3 Answers3

1

You want the window.load() event. Here's a jQuery example;

jQuery(window).load(function () {
    // page loaded, do stuff
});

You could also call this on a specific tag (<body>, for example) as onload="".

<body onload="...">
Jongosi
  • 2,305
  • 1
  • 28
  • 31
  • I have researched stuff and seen that. That won't work, but thanks for the suggestion. – Anonymous User Mar 04 '15 at 20:53
  • Ooohh, now that you added your code it's clearer; asynchronous queries don't *wait*, they are designed that way. However, see... http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done – Jongosi Mar 04 '15 at 20:56
  • Yes, I know they are designed that way, but this is added to page after load, and it never executes. I need a way to fix that. Thanks again, but not quite what I need. – Anonymous User Mar 04 '15 at 21:02
1

jQuery

$(document).ready(function() {
  // DOM Loaded
});

JavaScript

document.onload = function() {
  // DOM loaded
};
Eric Clifford
  • 223
  • 3
  • 8
0

After sitting on the problem and thinking about it, I realized that what I was trying to do won't work. The PHP is translated before the page is loaded on the screen at the server, and then after it loads, nothing else can happen. I need to move this over to the client and to JavaScript. Thanks though, and sorry for posting an impossible question!