[javascript] 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)?

This question is related to javascript ajax

The answer is


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.


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


It's even easier to do without a library

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