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.

6
  • 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? Commented Jan 7, 2019 at 3: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. Commented Jan 7, 2019 at 3: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? Commented Jan 7, 2019 at 3:22
  • @Jonathan still get the not defined error Commented Jan 7, 2019 at 3:26
  • @Jonathan smh, it was google chrome, not clearing the cache when I reload the page. Everything works from IE just fine... Commented Jan 7, 2019 at 3:30

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.