1
$.getScript("/js/my.js")
    .done(function(script, textStatus) {
        console.log(script);
        myFunction();
    })
    .fail(function(jqxhr, settings, exception) {
        $("div.log").text("Triggered ajaxError handler.");
    });

The script argument in .done returns my entire js file which also includes myFunction(). However I get the error Uncaught ReferenceError: myFunction is not defined

my.js

$(function () {
     function myFunction() {
        console.log("Worked!")
    }
}); 
LEE
  • 3,335
  • 8
  • 40
  • 70
  • 1
    Is the `myFuntction()` defined in your js file declared globally? or atleast available via a namespace `windows.myScript.myFunction()` – Jaya Sep 08 '17 at 17:08
  • is `myFunction()` written correctly? Might there be any errors in the external js file? Without a [complete example](https://stackoverflow.com/help/mcve) this is impossible to troubleshoot. – Tijmen Sep 08 '17 at 17:14
  • you need to post the code of how `myFunction` is defined within `my.js` – adiga Sep 08 '17 at 17:15
  • Just edited the answer. – LEE Sep 08 '17 at 17:23

2 Answers2

0

I tried your code and the only error I have is the fact that do not know anything about parameter you are passing

Uncaught ReferenceError: argument is not defined

If I remove the parameter and call your function like:

.done(function(script, textStatus) {
        console.log(script);
        myFunction();
    }

Is working fine.

Make sure the name of the function inside the JS file is exactly myFunction. Maybe re-create it to avoid special characters.

Fully working example for me:

From JSP:

$.getScript("<%=request.getContextPath()%>/resources/js/my.js")
    .done(function(script, textStatus) {
        console.log(script);
        myFunction();
    })
    .fail(function(jqxhr, settings, exception) {
        $("div.log").text("Triggered ajaxError handler.");
    });

webapp\resources\js\my.js

function myFunction() {
    console.log("Worked!")
}
Ermal
  • 441
  • 5
  • 19
  • Ok. I'll check what the issue is. Function name is exactly the same. – LEE Sep 08 '17 at 17:27
  • With the update you did to the question I see that the way you have defined the function is "not ok"...I am going to update my answer how the function should be in order to call it simply by name as you are calling – Ermal Sep 08 '17 at 17:37
0

Fixed using the following. Reference -> this Basically got the idea from you guys regarding the global variable thing.

Inside my.js

MyObject = {
        abc: function () {
            console.log("Worked")
        }
    }

And I called it this way MyObject.abc() inside .done

LEE
  • 3,335
  • 8
  • 40
  • 70