Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Ajax call after page load

How do we make ajax call after page load.

I need to make a ajax call suppose after 10sec document has loaded.

function loadajax(){
  $.ajax({ 
    url:'test',
    data:"username=test",
    type:"post",
    success:function(){
     //do action
    }
  });
}
 $('document').load(function(){
setTimeout(function(){
   loadajax();
 },10000);

});

I am doing it in this way. But doesn't succeeded.

like image 631
Anil Sharma Avatar asked May 05 '14 13:05

Anil Sharma


3 Answers

So many answers, all slightly different, but the shortest recommended syntax to run the function 10 seconds after DOM ready, while still retaining best practices, would be:

$(function(){
    setTimeout(loadajax,10000);
});

As Blazemonger mentions below, you could simply put setTimeout(loadajax,10000); at the end of the document, however that is not as flexible to change. jQuery DOM load code should always be in a jQuery DOM load event (i.e. $(function(){...});)

like image 144
Gone Coding Avatar answered Oct 17 '22 11:10

Gone Coding


1000 is in milliseconds -- ten seconds would be 10000. Also, you're looking for $(document).ready:

$(document).ready(function(){
    setTimeout(function(){
       loadajax();
     },10000); // milliseconds
});

http://api.jquery.com/ready

like image 5
Blazemonger Avatar answered Oct 17 '22 12:10

Blazemonger


Try it like this

$(function(){
  loadajax();
});
like image 1
djbielejeski Avatar answered Oct 17 '22 10:10

djbielejeski