SoldierCorp SoldierCorp - 13 days ago 4
HTML Question

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.

Answer

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() { /* ... */}.

Comments