javascriptjqueryajaxjavascript-namespaces

javascript access function from another namespace in namespaced ajax functions callback


I need some help with my javascript code. I just recently started using namespaces and I have a problem which I am not able to solve.

I have two files data.js and themes.js with a namespace on each data and themes respectively. On data namespace I have a function to perform an ajax call like this:

var data = data || {};data = {
    get_companies: function (id) {
        $.ajax({
            //blah blah blah
        });
    }
}

and in the themes namespace i have a function like this:

var themes = themes || {};
themes = {
    themeAdd: function () {
    //blah blah
        $.ajax({
            //blah blah
            success: function (data) {
                data.get_companies('#someid');
            }
        });
    }
}

The problem is, while I can access data.get_companies from themes.js file and console, when I try to call it inside ajax callback it produces an error (data.get_companies is not a function). How can I fix that and why I can't access this function in ajax callbacks?


Solution

  • In your ajax success callback change the name of the argument passed to it:

    $.ajax({
        //blah blah
        success: function (response) {
            data.get_companies('#someid');
        }
    };
    

    At the moment you define an anonymous function with an arument called data, so inside this function data is what has been received by AJAX request, not your global data object.

    You could also try to access it like this:

    $.ajax({
        //blah blah
        success: function (data) {
            window.data.get_companies('#someid');
        }
    };