Search code examples
javascriptphpjqueryinitializationdocument-ready

Initializing a variable in script at .php page and not getting it in .js file


In my .php page at bottom

(function ($) {
    $(document).ready(function () {
        var Atest = 'Hi';

        $.getScript(app_consts.VIEW_JS + 'something.js');
    });
})(jQuery);

In the something.js file I have writen

(function ($) {
    $(document).ready(function () {
        console.log(Atest);
    });
})(jQuery);

And in the console value is not printed. I don't know how to get that.


Solution

  • Change scope of variable like..

    <script type="text/javascript">
        var Atest = 'Hi';
    
        (function ($) {
        $(document).ready(function () {
            //var Atest = 'Hi';
    
            $.getScript(app_consts.VIEW_JS + 'something.js');
        });
        })(jQuery);
    </script>
    

    you can read more about Javascript Scope from here.