1

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!

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

3 Comments

I didn't think about the asynchronicity of ajax. Thank you very much!
@Sebsemillia: you're most welcome. The "A" is for asynchronous! (But then again the "X" is for "XML", so maybe the acronym isn't particularly relevant.)
Hehe, I know! But now I will remember.. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.