0

I have a select in my html and would like to add the options via ajax when the page loads. The options values are in my DB and I get them via a call to ajax. To do so, I'm writing a class in javascript but I just can't get my data when it runs. Please take a look :

--- Main.js ---

function MyLoader() {
    this._clients = null;
    this._code = null;
}

Loader.prototype = {

    var context = this;

    loadClients: function() {
        $.ajax({
            url: "my/php/",
            type: "POST",
            data: {...},
            success: function(response) {
                context._clients = response;
            }
        });
    },

    getCode: function() {...}
};

Then I have the following :

$(document).ready(function() {
    var loader = new Loader();
    loader.loadClients();
    alert(loader._clients);

    //Here I want to add my options to the select
});

My alert always returns null, and I don't understand why. I need to save my data in the class in order to access them anytime I need to.

Can you point me to the right direction to make all my stuff work ? Thank you for your answers.

3 Answers 3

1
Loader.prototype = { //     v---callback parameter
    loadClients: function(callback) {
        $.ajax({
            url: "my/php/",
            context: this, // <---set success context
            type: "POST",
            data: {...},
            success: callback // <---pass callback
        });
    },

    getCode: function() {...}
};

$(document).ready(function() {
    var loader = new Loader();
                      //  v---pass callback
    loader.loadClients(function(response) {
        this._clients = response;
        alert(this._clients);
        //Here I want to add my options to the select
    });

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

Comments

0

I believe that you need to do all of your dynamic loading inside of your 'success' callback, since it is loading asynchronously.

Comments

0

You need to do it inside the success callback since it's async:

Loader.prototype = {

    var context = this;

    loadClients: function() {
        $.ajax({
            url: "my/php/",
            type: "POST",
            data: {...},
            success: function(response) {
                context._clients = response;
                alert(loader._clients);

               //Here I want to add my options to the select
            }
        });
    },

    getCode: function() {...}
};

$(document).ready(function() {
    var loader = new Loader();
    loader.loadClients();
});

Comments

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.