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');
    }
}
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));
  • Adrian, Thank you very much! But what is this "use strict" and "use script" your passing? Sorry, i cant understand the function very well – Vinicius Souza Feb 1 '18 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 Feb 1 '18 at 18:27
  • I would never think of that... how did you figure it? – Vinicius Souza Feb 1 '18 at 18:31
  • It's the same issue as trying to use any merge field in a Static Resource. – Adrian Larson Feb 1 '18 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? – Vinicius Souza Feb 2 '18 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.