0

I am trying to accomplish something similar to: Calling a function from one JavaScript file which requires another

Essentially, I have index.php, which is the main file for the home page. Within the index file, I am calling a javascript function from another js file.

<script src="js/data.js"></script>
<script>(go_call())</script>

within data.js:

function go_call(){
     alert('working');
}

I get the following error: Uncaught ReferenceError: go_call is not defined

UPDATE 1:

My original code is working fine in IE, but this error I have occurs in google chrome.

dataviews
  • 2,466
  • 7
  • 31
  • 64
  • have you checked your path to the JS file is correct? (that it's not 404 in the console). Your code sample doesn't show async, but I'll ask anyway... are you loading the .js file asynchronously? – Jonathan Jan 07 '19 at 03:16
  • @Jonathan no additional errors present in console, and I am not loading asynchronously. Once I declare js/data.js shouldn't I be able to call that function at a later time? I also tried the Ajax method (getScript) and that does work, but there is other code within the data.js file that I don't want to reload just to call that function. – dataviews Jan 07 '19 at 03:20
  • 1
    This isn't really good practice, but, can you test something for me... in your data.js file, instead of `function go_call() {`, change it to `window.go_call = function() {` and see if the error stops? – Jonathan Jan 07 '19 at 03:22
  • @Jonathan still get the not defined error – dataviews Jan 07 '19 at 03:26
  • @Jonathan smh, it was google chrome, not clearing the cache when I reload the page. Everything works from IE just fine... – dataviews Jan 07 '19 at 03:30
  • @Jonathan so my original code actually works in IE, but not in google chrome, unless my browser is still not refreshing properly. – dataviews Jan 07 '19 at 03:33

1 Answers1

0
A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

A function cannot be called unless it is in the same or greater scope then the one trying to call it.
It should work like this:

1) within data.js
function go_call(){
alert('working');
}

2) Within file2.js
function clickedTheButton() {
go_call();
}

3) Html File:
<html>
<head>
</head>
<body>
<button onclick="clickedTheButton()">Click me</button>
<script type="text/javascript" src="data.js"></script>
<script type="text/javascript" src="file2.js"></script>
</body>
</html>
S.Maneesh
  • 60
  • 6
  • I am calling the function after I referenced it. go_call() function is defined in data.js, which is being referenced before I make the function call. – dataviews Jan 07 '19 at 03:27