Hector Barbossa
Hector Barbossa

Reputation: 5528

Javascript ajax call on page onload

I wish a page to fully load before issuing an ajax call to update database. I can call a javascript function in the body onload event so the page is fully loaded, but I'm not sure how to trigger the Ajax call from there.Is there any better way of achieiving this (Upadating database after page load)?

Upvotes: 28

Views: 253059

Answers (4)

Eero
Eero

Reputation: 4754

This is really easy using a JavaScript library, e.g. using jQuery you could write:

$(document).ready(function(){
    $.ajax({ url: "database/update.html",
        context: document.body,
        success: function(){
           alert("done");
        }
    });
});

Without jQuery, the simplest version might be as follows, but it does not account for browser differences or error handling:

<html>
    <body onload="updateDB();">
    </body>
    <script language="javascript">
        function updateDB() {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "database/update.html", true);
            xhr.send(null);
            /* ignore result */
        }
    </script>
</html>

See also:

Upvotes: 62

Chris Broski
Chris Broski

Reputation: 2550

It's even easier to do without a library

window.onload = function() {
    // code
};

Upvotes: 6

JST
JST

Reputation: 1174

Or with Prototype:

Event.observe(this, 'load', function() { new Ajax.Request(... ) );

Or better, define the function elsewhere rather than inline, then:

Event.observe(this, 'load', functionName );

You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();").

However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.

Upvotes: 4

Trecenti
Trecenti

Reputation: 81

You can use jQuery to do that for you.

 $(document).ready(function() {
   // put Ajax here.
 });

Check it here:

http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29

Upvotes: 8

Related Questions