I am trying to write an ajax web app. I have a function that is suppose to request a json object and then use it to re/populate the website.
Here is the Javascript in Question (Lines 8 – 16):
window.onload=LoadData("Home", {});
var _doc = {};
function LoadData(page, params) {
$.get(page, params, function ( data ) {
_doc = jQuery.parseJSON( data );
}
);
document.title = _doc.Title.Title;
};
Here is the error Chrome gave:
Uncaught TypeError: Cannot read property 'Title' of undefined
LoadDatahttp://127.0.0.1/:15
(anonymous function)
This is what has me confused if I run the same statement in the console:
document.title = _doc.Title.Title;
"Home"
And it changes the title to Home
Here is proof that its not undefined:
_doc
Object
Body: Object
Menus: Array[4]
0: Object
Menu: Object
1: Object
Menu: Object
2: Object
Menu: Object
3: Object
Menu: Object
Title: Object
Title: "Home"
User: Object
Name: "Username"
And A screenshot as an overview:

Note: the call to the function at the bottom did change the title
You can only access the
datafrom the AJAX request in the callback:AJAX requests (Asynchronous JavaScript and XML) requests are asynchronous; the browser initiates the request, and does not wait for a response… instead the JavaScript execution is continued. Some time later, when the HTTP request for the AJAX request has completed, the callback you provided for the AJAX request is invoked, and has access to the data contained in the HTTP response.
In your situation,
document.title = _doc.Title.Title;is executed immediately after the AJAX request is dispatched (i.e. before the some time later mentioned above has occured); so the callback_doc = jQuery.parseJSON( data );has not fired yet, so_docis still an empty object, so_doc.Titleis undefined, and trying to retrieveTitleon the undefined_doc.Titleis throwing the error.Unrelated to your problem, but FYI, you might want to look at the
jQuery.getJSONmethod; the difference between that that thejQuery.getmethod is that the response object you get passed will already be the JSON object (so you won’t need to calljQuery.parseJSON).