3

i was doing a page/script/controller functionality just see how it works, and for some reason i get the error "Visualforce is not defined".

From what i got searching, this error shows when you dont add the controller to your page, but in my case it is there, heres the code:

Page:

<apex:page controller="ControllerTest" sidebar="false">
<apex:pageBlock>
<apex:pageBlockSection>
<p id="test">
Click
</p>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:includeScript value="{!$Resource.testScript}" loadOnReady="true" />
</apex:page>

Script:

const button = document.getElementById("test");
console.log("Script OK");
Visualforce.remoting.timeout = 120000;
function testFunction(){
    Visualforce.remoting.Manager.invokeAction('ControllerTest.test', (result, event){
                                                  console.log("invokeAction Okay!");
                                              });
}

button.onclick = () => {
    testFunction();
}

Controller:

    public class ControllerTest{
    public ControllerTest(){}


    public static void test(){
        System.debug('Gotcha');
    }
}

1 Answer 1

4

You can't directly reference remoting functions within an external script. Either define them on your page or pass them around in a globally visible object. The latter would look something like:

<apex:page controller="MyController">
    (function (w) {
        "use strict";
        w.MyRemoter = w.MyRemoter || {};
        w.MyRemoter.invoke = Visualforce.remoting.Manager.invokeAction;
        Object.freeze(w.MyRemoter);
    }(window));
</apex:page>

Then in your script you can reference this object and invoke it:

(function (w) {
    "use strict";
    w.MyRemoter = w.MyRemoter || {};
    var myFunction = function () {
        w.MyRemoter.invoke('MyController.doStuff', function (result, event) {
            console.debug(result);
        });
    }
}(window));
5
  • Adrian, Thank you very much! But what is this "use strict" and "use script" your passing? Sorry, i cant understand the function very well Commented Feb 1, 2018 at 18:23
  • The key point I'm trying to get across is you have to add the function to the window if you want to access the script in a Static Resource instead of on your Visualforce Page.
    – Adrian Larson
    Commented Feb 1, 2018 at 18:27
  • I would never think of that... how did you figure it? Commented Feb 1, 2018 at 18:31
  • It's the same issue as trying to use any merge field in a Static Resource.
    – Adrian Larson
    Commented Feb 1, 2018 at 18:32
  • Hey, im trying to implement this but for some reason its giving me "this.getAction is not a function" when i try to call the invoke from the external js file, can you help me? Commented Feb 2, 2018 at 11:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .