hyde
hyde

Reputation: 2585

Load content using AJAX on window.onload

I am trying load some JSON data from a PHP backend, parse them and populate a div based on the JSON data I receive. I want to do this as soon as the window has been done loading. Right now I have it setup like this:

$(function(){
    $.getJSON("todo_action.php?getall=true", function(data){
        console.log(data);
    });
});

However, this approach is not working. But after the window has been done loading and I go to Chrome's developer console and run the code above, it works. Correct me if I am wrong, but I think this is not working because by default all AJAX requests are asynchronous and it has to do with the asynchronous property of AJAX, right?

I tried other variants of jQuery's built in AJAX functions like get, load, ajax but no avail. I have also tried making the request synchronous using $.ajaxSetup({async: false}); and it still does not work.

Upvotes: 0

Views: 2616

Answers (2)

rossipedia
rossipedia

Reputation: 59367

Are you sure you're not just missing a closing );?

$(function(){
    $.getJSON("todo_action.php?getall=true", function(data){
        console.log(data);
    });
}); // <- here

It should work fine, I have an example JsFiddle here.

Upvotes: 3

Colt Stumpf
Colt Stumpf

Reputation: 121

Make sure the page is fully loaded.

$(window).load(function() {
 // executes when complete page is fully loaded, including all frames, objects and images
 $.getJSON("todo_action.php?getall=true", function(data){
        console.log(data);
    });
});

Upvotes: 0

Related Questions