Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ajax call on page onload

Tags:

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)?

like image 796
Hector Barbossa Avatar asked Nov 10 '10 13:11

Hector Barbossa


People also ask

How do I run Ajax in document ready?

If you're on Chrome, open Developer Tools (F12), go to Network - click on Filter icon and select XHR, reload the page again using F5, if you don't see ur call there, then the call itself is not fired. You can check if there're are any errors in Console tab of Dev Tools.

Which function is used to load a resource in the background in Ajax?

callback − A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code.

Which method is used on the returned object of Ajax () method if the Ajax call fails?

If an AJAX request fails, you can react to the failure inside the callback function added via the fail() function of the object returned by the $. ajax() function. Here is a jQuery AJAX error handling example: var jqxhr = $.


1 Answers

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:

  • Launching Code on Document Ready
  • jQuery ajax
  • http://msdn.microsoft.com/en-us/library/ms535874(VS.85).aspx
like image 90
Eero Avatar answered Sep 21 '22 19:09

Eero