0

I am looking to call an external REST API when a user clicks on a button in Salesforce classic. After some research I found I can use the javascript below and the content of sforce.connection.remoteFunction gets executed. This works fine to fetch an Auth Token. However this is just the first step, and I then need to call the REST API a second time in the function runBot(). How can I also trigger a second call to the API with just one button?

xhr = new XMLHttpRequest(); 
xhr.open( "GET", "/soap/ajax/11.0/connection.js", false); 
xhr.send(); 
eval(xhr.responseText); 

function runBot(token){
    alert('My token is ' + token);
    alert('The case is ' + {!case.Id});
}

sforce.connection.remoteFunction(
{ 
    url : 'https://myCloudApp/v1/authentication',
    method: "POST",    
    requestData: '{"username": "my.username", "password": "Password1" }',
    requestHeaders: { 
        'Content-Type': 'application/json'
    }, 
    onSuccess : function(response) { 
        alert('success'); 
        var obj = JSON.parse(response);
        token = obj.token;
        result = runBot(token);
    }, 
    onFailure : function(response) { 
        alert('Failed ' + response); 
    }
});
0

Aha! I just realised the reference to sforce.connection.remoteFunction is simply a call to a built-in function...which I can do as many times as I like. So altering the code as follows works fine:

onSuccess : function(response) { 
     alert('success'); 
     var obj = JSON.parse(response);
     token = obj.token;

     //second call to external API
     //----------------------------------------------
     sforce.connection.remoteFunction(
     { 
       ...details of REST call
     }, 
}

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.