user558134
user558134

Reputation: 1129

Jquery - run $.ajax() on window load

I was wondering if it is possible to use $.ajax() inside window load and get data from a php file. If not then what alternatives do I have?

$(window).load(function() {
 $.ajax({
  type: 'POST',
  url: file.php,
  data: data,
  success: function(data) {
   // to do
  }
 });
});

Thanks!

Upvotes: 1

Views: 4965

Answers (2)

tiagoboldt
tiagoboldt

Reputation: 2426

Sure is. It's executed once the page is loaded. A more common method is using ready() but I guess it should work anyway.

Upvotes: 0

Mörre
Mörre

Reputation: 5723

The data seems a little incomplete, for example, do you have any issues, or how do you load jquery and your own code into the page, so I may answer the wrong question :)

First, have a look at, for a good example, http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/ Do you really want the load event, or wouldn't the ready event be better?

Second, if you don't need the DOM but just want to start the AJAX call asap don't wait for either event - just issue the call. At that point you must already have loaded jquery at least anway, so you are all set for starting an AJAX call early, page still loading or not. If you DO want to work on the DOM, still issue the AJAX call right away - and put the ready (or load) event listening into the AJAX success function.

Upvotes: 2

Related Questions