Friday, 24 November 2017

Javascript ajax call on page onload

Javascript ajax call on page onload


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");
        }});
});

ContentMiddleAd

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

   onload="updateDB();">
  
  

ContentMiddleAd

See also:

Sol 2:

You can use jQuery to do that for you.
 $(document).ready(function() {
   // put Ajax here.
 });
Check it here:

Sol 3:

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.







No comments:

Post a Comment