Sebsemillia
Sebsemillia

Reputation: 9476

Access javascript object created in a function

I'm making my first steps with javascript objects combined with php objects. So far everything is working fine, but I struggle to access the javascript object created in the ajax success response outside of this function.

Here is my JS code:

function settings(mannstage, stundenlohn, tags) {
    this.mannstage = mannstage;
    this.stundenlohn = stundenlohn;
    this.tags = tags;
}
var currentSettings;
SendAjaxJsonRequest("getSettings");

function SendAjaxJsonRequest(method, jsonObject) {
    jsonObject = (typeof jsonObject === "undefined") ? "none" : jsonObject;
    $.ajax({
        type: "POST",
        url: "app/class/controller/ajax.php",
        data: {
            method: method,
            jsonObject: jsonObject
        },
        success: onSuccess
    })
};

function onSuccess(content) {

    var response = $.parseJSON(content);
    currentSettings = new settings(response.mannstage, response.stundenlohn, response.tags);
    console.log(currentSettings); //Returns the object
}
console.log(currentSettings); //This is undefined

The last console.log is undefined. How can I make currentSettingsaccessible outside the onSuccess function?

Thank you!

Upvotes: 1

Views: 89

Answers (2)

Subash Selvaraj
Subash Selvaraj

Reputation: 3385

Ajax is asynchronous, so the last console.log will be executed before the success function is called.

Upvotes: 2

Paul D. Waite
Paul D. Waite

Reputation: 98816

currentSettings is accessible outside the onSuccess function, but your last console.log call runs immediately after onSuccess is defined, which is before it's been called, so the value of currentSettings is still undefined at that point.

Maybe editing your code like this will demonstrate it:

function onSuccess(content) {

    var response = $.parseJSON(content);
    currentSettings = new settings(response.mannstage, response.stundenlohn, response.tags);
    console.log(currentSettings); //Returns the object
    afterSuccess(); // Also returns the object
}

function afterSuccess() {
    console.log(currentSettings);
}

Upvotes: 1

Related Questions