Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError:foobar is not defined (anonymous function)

I have this js file serving from some domain say foobar.com

at http://foobar.com/static/js/main.js:

$(document).ready(function() {
        function foobar(bar){
            $.ajax({
                    url: "/site/foo/",
                data: {'foo':bar},
                    dataType: "jsonp",
                    crossdomain: !0,
                    success: function (data) {
                alert(data);
                    },
                    error: function () {
                    }
                })
        }   
    });

On barfoo.com on some url, I have something like this:

<script src='http://foobar.com/static/js/main.js' type='text/javascript'></script>
<script type='text/javascript'>foobar('123456')</script>

When I hit that url : it says

Uncaught ReferenceError:foobar is not defined (anonymous function)

How to access function from other domains?

like image 543
Tauquir Avatar asked Dec 22 '22 04:12

Tauquir


1 Answers

You've defined "foobar()" inside the "ready" handler. It's therefore a local variable in that function, and invisible outside it.

You could add this to the end of the "ready" handler:

  window['foobar'] = foobar;

and then it'd be visible globally.

By the way this is something that can bite at jsfiddle because it (by default) will wrap code in a "load" handler. Thus, if you copy/paste from a JavaScript file included in the <head>, a function that would be global in that context ends up not global in the fiddle.

like image 103
Pointy Avatar answered Dec 24 '22 02:12

Pointy