user891859 user891859 - 9 months ago 41
Javascript Question

Salesforce - Executing Javascript through Apex Controller

Im new to Salesforce in general and Im trying to decide how to handle the invoking of a SOAP webservice. Currently the webservice is being executed via AJAX when a user clicks a button on the Opportunity page. I have been asked to move the webservice invocation from the button and place it into a custom controller page. So the webservice needs to be invoked seamlessly when certain conditions are met, opposed to having the user click a button.

I'd like to just kick off the webservice using the same ajax statement because it will save me time. Although it would seem to make more sense to invoke the webservice via Apex, but am still researching that topic. So here is my question:

Is it possible to execute the following javascript from within an Apex controller? If so how?

{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}
var xfolder = "MyNewFolder"
var parentid = "999999999999999"
var myvar = sforce.apex.execute("myWS","invokeExternalWs", {folderName:xfolder,ObjectID:parentid});
window.alert('Folder created: ' + myvar);

Answer Source

Read these reference documents thoroughly first: Action Functions, Apex in Ajax, or Visualforce JavaScript Remoting.

The easiest way to do what you're asking is to include the connection.js and apex.js files on the page using an <apex:includeScript> tag (like below).

<apex:includeScript value="/soap/ajax/24.0/connection.js"/>
<apex:includeScript value="/soap/ajax/24.0/apex.js"/>

Then, put your JavaScript in a function in a <script> tag under the <page> tag.

<script>
    function invokeWebService()
    {
        var xfolder = "MyNewFolder"
        var parentid = "999999999999999"
        var myvar = sforce.apex.execute("myWS","invokeExternalWs", {folderName:xfolder,ObjectID:parentid});
        window.alert('Folder created: ' + myvar);
    }
</script>

Finally, call your function with the onclick attribute on an input button.

<button type="button" onclick="invokeWebService();" style="btn">Invoke</button>

Note.. I haven't tested any of this, but it should work with minor tweaks (I've used a similar approach many times).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download