Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call external function inside jquery code from html?

I need to load function to get data from external JS included in HTML file, and I'm doing this:

<body onLoad="getTicket();">
......
</body>

or this:

<html>
<body>
    <head>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script src="js/functions.js" type="text/javascript"></script>
    <script>
        $(document).ready(function() {
            getTicket();
        });
    <script>
    </head>
<body>
</html>

or this:

<html>
<body>
    <head>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script src="js/functions.js" type="text/javascript"></script>
    <script>
        getTicket();
    <script>
    </head>
<body>
</html>

And I have this in functions.JS:

functioOne() {

}

functionTwo() {

}

$(document).ready(function() {
    ...
    .....
    function getTicket() {
        //to do
    }
});

But does'nt work and in the console display this:

Uncaught ReferenceError: getTicket is not defined 

Regards.

like image 297
SoldierCorp Avatar asked Feb 16 '13 08:02

SoldierCorp


2 Answers

Your getTicket function is defined only in the context (scope) of the jQuery closure (anonymous function). Define it in the global scope instead (elsewhere in the file and not as a "function parameter").

If you need variables from that scope, encapsulate them in a namespace (an object), or declare it as window.getTicket = function() { /* ... */}.

like image 59
Camilo Martin Avatar answered Oct 26 '22 23:10

Camilo Martin


Try putting the function getTicket(){} outside or the doc ready:

functio One() {

}

function Two() {

}
function getTicket() {
    //to do
}

$(document).ready(function() {
...
.....
   getTicket();
});

Your order of inclusion is perfect no issues with that.

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/functions.js" type="text/javascript"></script>

This is perfectly fine.

like image 32
Jai Avatar answered Oct 26 '22 23:10

Jai