0

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?

4
  • first place your themes.js and then data.js , let see ? Hierachy matter Commented May 24, 2017 at 9:13
  • English is not my main language but i load them like that :<script src="public/history2/data.js"></script> <script src="public/history2/theme.js"></script> if thats what you mean.Also those two attach to click handlers so they are both loaded on call time Commented May 24, 2017 at 9:14
  • Got it - change it then try Commented May 24, 2017 at 9:15
  • var data = data || {}; data = { makes no sense. As soon you do data = { you're out of game, making data = data || {}; absolutely useless. Commented May 24, 2017 at 10:06

1 Answer 1

1

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');
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

works like charm!!!To understand better this is caused by naming collision between ajax argument and namespace??

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.