[SalesForce] Run javascript when clicking button on vf page

Previously I had a custom button on a custom object and I set behaviour to "execute javascript" and content source to "onclick javascript".

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
var retrieveDB = '{!Lead.Retrieve_DB_Details__c}';
if(retrieveDB == false){
alert('You cannot perform DB Check with retrieve DB details as false');
}
else{
var result = sforce.apex.execute("RetriveDBDetailsController","getDBDetails",{leadId:"{!Lead.Id}"});
alert(result);
window.location.reload();
}

But now I am creating a Visualforce page which contains a button.

<apex:commandButton action=" " value="D&B Check"/>

The question now is, how do I call a class by pressing a button on a Visualforce page?

I tried to write controller for the same :

public class D_B_LeadCntrlr {

public lead ld {get; set;}
public boolean Retrieve_DB_Details {get; set;}    
public String leadId {get; set;}
public D_B_LeadCntrlr(apexPages.StandardController sc){
    leadId = ApexPages.currentPage().getParameters().get('Id');
    if(leadId != null){
        ld = [select Retrieve_DB_Details__c from lead where id=:leadId limit 1];
        Retrieve_DB_Details = ld.Retrieve_DB_Details__c;
    }
}

public void callMethod(){
    system.debug('');
    RetriveDBDetailsController.getDBDetails(leadId);
   // pageReference pf = new pageReference('');
}

But having issue with alerts. Please help resolve this

VF Page :

<apex:page standardController="Lead" extensions="D_B_LeadCntrlr">
<apex:includeScript value="/soap/ajax/29.0/connection.js"/>
<apex:includeScript value="/soap/ajax/29.0/apex.js"/>
<script >

    var success = 'false';
    function myFunction(){
        var Retrieve_DB_Detail = '{!Retrieve_DB_Details}';
        if(Retrieve_DB_Detail == false || Retrieve_DB_Detail == 'false'){
            alert('You cannot perform DB Check with retrieve DB details as false');
        }else{
            var result = sforce.apex.execute("RetriveDBDetailsController","getDBDetails",{leadId:"{!leadId}"});
            alert(result);
             window.location.reload();
        }
    }

    function showSuccess(){
        if(showSuccess == 'true'){
            alert(success);
           window.location.reload();
        }
    }
    </script>
<apex:form >

    <apex:actionFunction name="callMethod" action="{!callMethod}" onComplete="showSuccess()"/>

        <apex:PageBlock >
            <div align="center" draggable="false" >
                <apex:CommandButton value="D&B Check" onclick="myFunction()" />
            </div>
        </apex:PageBlock>
    </apex:form>    
</apex:page>

Best Answer

Here is a try to simplify code :

VF Page:

<apex:page standardController="Lead" extensions="D_B_LeadCntrlr">

<script >


    function myFunction(){
        var Retrieve_DB_Detail = '{!Retrieve_DB_Details}';
        if(Retrieve_DB_Detail == false || Retrieve_DB_Detail == 'false'){
            alert('You cannot perform DB Check with retrieve DB details as false');
        }else{
            callMethod();
        }
    }

    </script>

<apex:form >
<apex:pagemessages />
    <apex:actionFunction name="callMethod" action="{!callMethod}"  />
        <apex:PageBlock >
            <div align="center" draggable="false" >
                <apex:CommandButton value="D&B Check" onclick="myFunction()"  onComplete="return null;"/>
            </div>
        </apex:PageBlock>
    </apex:form>    
</apex:page>

Apex:class:

public class D_B_LeadCntrlr {
public lead ld {get; set;}
public boolean Retrieve_DB_Details {get; set;}    
public String leadId {get; set;}
public D_B_LeadCntrlr(apexPages.StandardController sc){
    leadId = ApexPages.currentPage().getParameters().get('Id');
    if(leadId != null){
        ld = [select Retrieve_DB_Details__c from lead where id=:leadId limit 1];
        Retrieve_DB_Details = ld.Retrieve_DB_Details__c;
    }
}

public void callMethod(){
    system.debug('');    
    apexpages.Message msg = new Apexpages.Message(ApexPages.Severity.Info,RetriveDBDetailsController.getDBDetails(leadId));
    apexpages.addmessage(msg);
    }

}

How it will work:

  1. clicking button will call javascript function myFunction. Added oncomplete attribute to button to stop reloading of page on button click.
  2. Javascript function will perform initial check based on Retrieve_DB_Detail. if Retrieve_DB_Detail comes to be false it will call action function named callMethod.
  3. Action will call callMethod from apex controller and will add a pagemessage on page based on processing result.

Note that in order to make things simple second alert was modified to pagemessage. Also actionfunction will automatically perform refresh pf page.