function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
R R MR R M 

Onclick javascript button not working on Lightning

HI Folks, 
I have Onclick javascript button on Classic, now we need this button on Lightning pages, so i have developed lightning component but its not working not getting output, please do help. 

Original Onclick javascript button Code is :
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")} 

var result = sforce.apex.execute("GeneratingNewDocLinkForLoanInDB","GeneratingDocLink", {extrnlid:"{!Loan__c.Loan_External_id__c}"}); 
location.reload();

My Apex class : 

global class GeneratingNewDocLinkForLoanInDB
{
    public static string accToken;
    public static string accsToken;
    public static String expireTime;
    public static String tokenType;
    public static String refToken;
    public Static blob response;
    public static String endpointurl;
    public static string ResponseString;
    public static string blobResult; 
   
    //public static Loan_Doc_Details__c iLDetails = new Loan_Doc_Details__c(); 
    public static list<Loan_Doc_Details__c> lstUpdate = new list<Loan_Doc_Details__c>();
    public static long str;
    
       
    global static void returnToken() 
    {    
        //Custom Settings
        Generate_Loan_Doc_Url__c iCustom = [SELECT Name,ClientId__c,Client_Secret__c,Login_URL__c,Password__c,User_Name__c,Active__c,
                                       EndPoint__c FROM Generate_Loan_Doc_Url__c WHERE Active__c = true];
        system.debug('iCustom'+iCustom);
        
        String loginUri = iCustom.Login_URL__c;
        String clientId = iCustom.ClientId__c;
        String targetString = iCustom.Client_Secret__c;
        String clientSecret = EncodingUtil.urlEncode(targetString,'UTF-8');
        String username = iCustom.User_Name__c;
        String password = iCustom.Password__c;
        endpointurl = iCustom.EndPoint__c;
        String reqbody = 'client_id='+clientId+'&client_secret='+clientSecret+'&scope=partners_api_sensitive&grant_type=client_credentials';
        System.debug(reqbody);
        HttpRequest req = new HttpRequest(); 
        req.setMethod('POST');
        req.setHeader('content-type','application/x-www-form-urlencoded');
        req.setEndpoint(loginUri);
        req.setBody(reqbody);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        System.debug(res.getbody());
        
        //Custom Object - To check the access token expired or not
        Loan_Doc_Details__c iLDetails = [SELECT Id,Name,Access_Token__c,Active__c,Expiry_Time__c,Token_generated_time__c FROM Loan_Doc_Details__c 
                                            WHERE Active__c = true LIMIT 1];
        system.debug('iLDetails'+iLDetails);
        
        if(iLDetails.Token_generated_time__c != null){
        
            str = ((system.now().getTime() - iLDetails.Token_generated_time__c.getTime())/ 1000);
            system.debug(str);
        }
        
        system.debug(iLDetails.Access_Token__c);
        system.debug(iLDetails.Expiry_Time__c);
        
        if(iLDetails.Access_Token__c == '' || iLDetails.Access_Token__c == null || (iLDetails.Expiry_Time__c != null && str > iLDetails.Expiry_Time__c)){
            
            accessToken resp1 = (accessToken)JSON.deserialize(res.getbody(),accessToken.class);
            System.debug(resp1.access_token);
            accToken = resp1.access_token;System.debug(accToken);
            expireTime = resp1.expires_in;System.debug(expireTime);
            tokenType = resp1.token_type;System.debug(tokenType);
            
            //update custom object
            Loan_Doc_Details__c creds = new Loan_Doc_Details__c(Id = iLDetails.Id);
            system.debug('AccessToken length - '+accToken.length());
            creds.Access_Token__c = accToken;
            creds.Expiry_Time__c = decimal.valueof(expireTime);
            creds.Token_generated_time__c = system.now();
            system.debug('*****'+creds.Token_generated_time__c);
            lstUpdate.add(creds);
        
        } 
        else{
            accToken = iLDetails.Access_Token__c;
        }
    }

    Webservice static void GeneratingDocLink(String extrnlid)  
    {    
        returnToken();
        System.debug(extrnlid);

        Loan__c iloan = [SELECT ID,Loan_External_id__c FROM Loan__c WHERE Loan_External_id__c =:extrnlid];
        if(iloan.Loan_External_id__c !=null)
        {
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        req.setMethod('POST');
        system.debug(accToken);
        req.setHeader('Authorization', 'Bearer '+accToken);
        req.setHeader('Content-Type', 'application/octet-stream');
        System.debug('******'+endpointurl);
        String endpoint = endpointurl+'/'+iloan.Loan_External_id__c+'/'+'documents';
        system.debug(endpoint);
        req.setEndpoint(endpoint);
        req.setTimeout(100000);
        res = http.send(req);
        System.debug('******'+res.getbody());
        response = res.getbodyasblob();
        System.debug(Response);
               
        //update token details
        system.debug('*****'+lstUpdate);
        if(lstUpdate.size()>0){
            
            update lstUpdate;
        }      
       }        
    }  
    
    global class accessToken
    {
        public String id;
        public String access_token;
        public String expires_in;
        public String token_type;
    }
}
 


Using above code i have developed component and controller

Component :

<aura:component controller="GeneratingNewDocLinkForLoanInDB"
implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction,force:hasSObjectName,lightning:actionOverride" access="global" >
	<ui:button label="Generate Document" press="{!c.Generatedoc}"/>
</aura:component>
 

Controller :

({
Generatedoc :function(component,event, helper){	
var result = (sforce.apex.execute("GeneratingNewDocLinkForLoanInDB","GeneratingDocLink", {extrnlid:"{!Loan__c.Loan_External_id__c}"})); 
location.reload();
}
})
 

Then added Quick action(TestButton) on Lightning page.

When i am clicking on TestButton getting popup with "Generate Document" Button. then when i clicks on  "Generate Document" button it is just reloading the page and not getting any output 

Best Answer chosen by R R M
R R MR R M

Prepare VF  and changed Button Code.
Vf page : Apexstart 

<apex:page controller="ApexStartController" title="Start Process" showHeader="false" standardStylesheets="false" docType="html-5.0" applyHtmlTag="false" applyBodyTag="false" id="a">
<apex:slds /> 
<html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<head>
  <apex:includeScript value="/soap/ajax/36.0/connection.js"/>
  <apex:includeScript value="/soap/ajax/36.0/apex.js"/>
  <apex:stylesheet value="/resource/1512720834000/ZestLogo.css" />
</head>
<body>
 <apex:form id="f">
  <div class="slds-modal__container">
    <div class="slds-modal__header slds-theme--info">
      <div class="slds-media__figure">
      <div class="slds-modal__header slds-theme--default">
    <apex:commandButton value="Generate Docs Link" action="{!doStart}" styleClass="slds-button slds-button--brand" />&nbsp;&nbsp;
      <apex:commandButton value="Cancel" action="{!doCancel}" styleClass="slds-button slds-button--neutral"/>
      
    </div>
          <svg aria-hidden="true" class="slds-icon slds-icon--small">
              <!--<use xlink:href="{!URLFOR($Resource.SLDS214, '/assets/icons/utility-sprite/svg/symbols.svg#process')}"></use>!-->
          </svg>
        </div>
      <h2 class="slds-text-heading--medium">{!q}</h2>
    </div>

    <div class="slds-modal__content slds-p-around--medium" style="min-height:80px">
        <apex:outputPanel id="result" layout="block" rendered="{!execScript}">
            <div class="slds-spinner--brand slds-spinner slds-spinner--small" role="alert">
                <span class="slds-assistive-text">Processing</span>
                <div class="slds-spinner__dot-a"></div>
                <div class="slds-spinner__dot-b"></div>
            </div>
        </apex:outputPanel>
    </div>
    
    
  </div>

  <apex:outputPanel id="script" layout="none" rendered="{!execScript}">
  <script>
    sforce.connection.sessionId="{!GETSESSIONID()}";    
    // logistics    
    var resultId = "{!$Component.result}";
    var resultDiv = document.getElementById(resultId);
    var callback = {onSuccess: handleSuccess, onFailure: handleFailure};
    function handleSuccess(result, source) {
        resultDiv.innerText = result;
    }
    function handleFailure(error, source) {
        resultDiv.innerText = error;
    }
    // ApexCall
    var params = {};
    params["{!n}"] = "{!v}";
    var result = sforce.apex.execute ("{!c}", "{!m}", params, callback);
  </script>    
  </apex:outputPanel>
 </apex:form>
</body>
</html>
</apex:page>
 

Controller :

 

public with sharing class ApexStartController {
    public ApexStartController() {
        params = System.currentPageReference().getParameters();
        // System.debug(params);
        execScript = false;
    }
    /** Parameter */
    public Map<String,String> params { get; set; }
    /** Question */
    public String q {
        get {
            if (q == null) {
                q = params.get('q');
                if (q != null)
                    q = EncodingUtil.urlDecode(q, 'UTF-8');
            }
            return q;
        }
        set; 
    }
    /** Apex Class */
    public String c {
        get { return params.get('a'); }
        set; 
    }
    /** Apex Method */
    public String m {
        get { return params.get('m'); }
        set; 
    }
    /** Parameter Name */
    public String n {
        get { return params.get('n'); }
        set; 
    }
    /** Parameter Value */
    public String v {
        get { return params.get('v'); }
        set; 
    }

    public Boolean execScript { get; set; }
    
    public PageReference doStart() {
        execScript = true;
        return null;
    }

    public PageReference doCancel() {
        String r = params.get('r');
        if (r != null && r.length() > 0)
            return new PageReference(r);
        return null;
    }
}


Custom Button :​

While creating Custom button select Content Source is URL  and use below format

/apex/Apexstart?a=GeneratingNewDocLinkForLoanInDB&m=GeneratingDocLink&n=extrnlid&v={!Loan__c.Loan_External_id__c}
 

 

All Answers

sfdcMonkey.comsfdcMonkey.com
Hi R R M, 
add below method to you apex class :
@AuraEnabled 

  public static void AuraGeneratingDocLink(string currentRecId){
     string recId = currentRecId;
	 string extrnlid = '';
     for(Loan__c l : [select id,Loan_External_id__c from Loan__c WHERE ID =: recId]){
	    extrnlid = l.Loan_External_id__c;
	 }
	 if(extrnlid != ''){
	 GeneratingDocLink(extrnlid);
	 }
  }

update you javaScript controller code :
({
     Generatedoc :function(component,event, helper){	
       
	    var action = component.get("c.AuraGeneratingDocLink");
        action.setParams({
             "currentRecId": component.get("v.recordId")
        });
        
        action.setCallback(this, function(response) {
            if (response.getState() == "SUCCESS") {
              alert('success');
            }else{
			  alert('fail');
			}
        });
        $A.enqueueAction(action);

     }
})

i hope it helps you.
   Let me inform if it helps you and kindly mark it best answer if it helps you so it make proper solution for others
thanks 
sfdcmonkey.com 


 
R R MR R M

HI piyush_soni, 
i have used the code but not getting output. its just reloading the page and not getting any logs also.  
Need to POST the request to 3rd party system from Salesforce using this class and button. 
We are using the javascript button in Classic using the apex class which i mentioned above. 

please see the javascript code which we are using and we need to use same kind of in Lightning page to POST. 

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")} 

var result = sforce.apex.execute("GeneratingNewDocLinkForLoanInDB","GeneratingDocLink", {extrnlid:"{!Loan__c.Loan_External_id__c}"}); 
location.reload();

 

Please do help.

R R MR R M

Prepare VF  and changed Button Code.
Vf page : Apexstart 

<apex:page controller="ApexStartController" title="Start Process" showHeader="false" standardStylesheets="false" docType="html-5.0" applyHtmlTag="false" applyBodyTag="false" id="a">
<apex:slds /> 
<html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<head>
  <apex:includeScript value="/soap/ajax/36.0/connection.js"/>
  <apex:includeScript value="/soap/ajax/36.0/apex.js"/>
  <apex:stylesheet value="/resource/1512720834000/ZestLogo.css" />
</head>
<body>
 <apex:form id="f">
  <div class="slds-modal__container">
    <div class="slds-modal__header slds-theme--info">
      <div class="slds-media__figure">
      <div class="slds-modal__header slds-theme--default">
    <apex:commandButton value="Generate Docs Link" action="{!doStart}" styleClass="slds-button slds-button--brand" />&nbsp;&nbsp;
      <apex:commandButton value="Cancel" action="{!doCancel}" styleClass="slds-button slds-button--neutral"/>
      
    </div>
          <svg aria-hidden="true" class="slds-icon slds-icon--small">
              <!--<use xlink:href="{!URLFOR($Resource.SLDS214, '/assets/icons/utility-sprite/svg/symbols.svg#process')}"></use>!-->
          </svg>
        </div>
      <h2 class="slds-text-heading--medium">{!q}</h2>
    </div>

    <div class="slds-modal__content slds-p-around--medium" style="min-height:80px">
        <apex:outputPanel id="result" layout="block" rendered="{!execScript}">
            <div class="slds-spinner--brand slds-spinner slds-spinner--small" role="alert">
                <span class="slds-assistive-text">Processing</span>
                <div class="slds-spinner__dot-a"></div>
                <div class="slds-spinner__dot-b"></div>
            </div>
        </apex:outputPanel>
    </div>
    
    
  </div>

  <apex:outputPanel id="script" layout="none" rendered="{!execScript}">
  <script>
    sforce.connection.sessionId="{!GETSESSIONID()}";    
    // logistics    
    var resultId = "{!$Component.result}";
    var resultDiv = document.getElementById(resultId);
    var callback = {onSuccess: handleSuccess, onFailure: handleFailure};
    function handleSuccess(result, source) {
        resultDiv.innerText = result;
    }
    function handleFailure(error, source) {
        resultDiv.innerText = error;
    }
    // ApexCall
    var params = {};
    params["{!n}"] = "{!v}";
    var result = sforce.apex.execute ("{!c}", "{!m}", params, callback);
  </script>    
  </apex:outputPanel>
 </apex:form>
</body>
</html>
</apex:page>
 

Controller :

 

public with sharing class ApexStartController {
    public ApexStartController() {
        params = System.currentPageReference().getParameters();
        // System.debug(params);
        execScript = false;
    }
    /** Parameter */
    public Map<String,String> params { get; set; }
    /** Question */
    public String q {
        get {
            if (q == null) {
                q = params.get('q');
                if (q != null)
                    q = EncodingUtil.urlDecode(q, 'UTF-8');
            }
            return q;
        }
        set; 
    }
    /** Apex Class */
    public String c {
        get { return params.get('a'); }
        set; 
    }
    /** Apex Method */
    public String m {
        get { return params.get('m'); }
        set; 
    }
    /** Parameter Name */
    public String n {
        get { return params.get('n'); }
        set; 
    }
    /** Parameter Value */
    public String v {
        get { return params.get('v'); }
        set; 
    }

    public Boolean execScript { get; set; }
    
    public PageReference doStart() {
        execScript = true;
        return null;
    }

    public PageReference doCancel() {
        String r = params.get('r');
        if (r != null && r.length() > 0)
            return new PageReference(r);
        return null;
    }
}


Custom Button :​

While creating Custom button select Content Source is URL  and use below format

/apex/Apexstart?a=GeneratingNewDocLinkForLoanInDB&m=GeneratingDocLink&n=extrnlid&v={!Loan__c.Loan_External_id__c}
 

 

This was selected as the best answer