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
Akanksha CullenAkanksha Cullen 

Passing variables to Javascript function from apex command button

Hello,

I am trying to pass a variable from a custom lookup field on my visualforce pages which fetches the project's id as selected by the user and call the fetched id in my javascript function - run().

I have been able to fetch the project's id selected by the user, print the value in my div element within the html block but not able to succesfully pass the feteched id to the run function.

Step 1
User-added image
Project ID in the div :
User-added image

Although, I see the project's id in my javascript after i inspect the element on my browser. 

User-added image

Could anyone please help me with this issue.


Here's the code :
<apex:page controller="MyCustomLookupController" readOnly="true">
<apex:includeScript value="/soap/ajax/24.0/connection.js"/> 
<apex:includeScript value="/soap/ajax/24.0/apex.js"/>

    <apex:form id="myForm">  
        <apex:PageBlock id="PageBlock">  
            <apex:pageblocksection title="Project Estimation" >       
                 <apex:inputField id="Projects__c" value="{!contact.Project__c}"  />
             </apex:pageblocksection>
   
            
            <apex:pageblockbuttons location="top">
                <apex:commandButton value="Generate Estimation Chart!" onclick="run({!contact.Project__c})"></apex:commandButton>
            </apex:pageblockbuttons>
         </apex:PageBlock>
   
   
    </apex:form>
  <html>
  <body>
       <div class="chart" style="width: 90%">
           <div id="chart">{!contact.Project__c}</div>
       </div>
  </body>
  
  <script type="text/javascript"> 
  function openLookup(baseURL, width, modified, searchParam){
    var originalbaseURL = baseURL;
    var originalwidth = width;
    var originalmodified = modified;
    var originalsearchParam = searchParam;

    var lookupType = baseURL.substr(baseURL.length-3, 3);
    if (modified == '1') baseURL = baseURL + searchParam;

    var isCustomLookup = false;

    // Following "001" is the lookup type for Account object so change this as per your standard or custom object
    if(lookupType == "001"){

      var urlArr = baseURL.split("&");
      var txtId = '';
      if(urlArr.length > 2) {
        urlArr = urlArr[1].split('=');
        txtId = urlArr[1];
      }

      // Following is the url of Custom Lookup page. You need to change that accordingly
      baseURL = "/apex/CustomAccountLookup?txt=" + txtId;

      // Following is the id of apex:form control "myForm". You need to change that accordingly
      baseURL = baseURL + "&frm=" + escapeUTF("{!$Component.myForm}");
      if (modified == '1') {
        baseURL = baseURL + "&lksearch=" + searchParam;
      }

      // Following is the ID of inputField that is the lookup to be customized as custom lookup
      if(txtId.indexOf('Projects__c') > -1 ){
        isCustomLookup = true;
      }
    }


    if(isCustomLookup == true){
      openPopup(baseURL, "lookup", 350, 480, "width="+width+",height=480,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
    }
    else {
      if (modified == '1') originalbaseURL = originalbaseURL + originalsearchParam;
      openPopup(originalbaseURL, "lookup", 350, 480, "width="+originalwidth+",height=480,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
    } 
   }
   
   function run(){ 
    alert('{!contact.Project__c}'); 
    var query = "SELECT End_Date__c, Duration__c,Project__c, Actual_End_Date__c, Progress__c FROM Tasks__c WHERE Project__c:= {!contact.Project__c}";   //Records from dependency table
    sforce.connection.sessionId = "{!$Api.Session_ID}";  
    var records = sforce.connection.query(query); 
    var records1 = records.getArray('records');
    alert('Initial records:'+records1);
   }
  
</script>
</html>
</apex:page>

 
Best Answer chosen by Akanksha Cullen
Himanshu ParasharHimanshu Parashar
Hi Akanksha,

The problem is you have created run function without parameter and you are calling run function with parameter. kindly modify your function as 
 
function run (paramval)
{
alert(paramval);
var query = "SELECT End_Date__c, Duration__c,Project__c, Actual_End_Date__c, Progress__c FROM Tasks__c WHERE Project__c:= {!contact.Project__c}";   //Records from dependency table
sforce.connection.sessionId = "{!$Api.Session_ID}"; 
var records = sforce.connection.query(query);
var records1 = records.getArray('records');
alert('Initial records:'+records1);
}
}

and
 
onclick="run('{!contact.Project__c}')"


Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S.  If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
 

All Answers

Himanshu ParasharHimanshu Parashar
Hi Akanksha,

The problem is you have created run function without parameter and you are calling run function with parameter. kindly modify your function as 
 
function run (paramval)
{
alert(paramval);
var query = "SELECT End_Date__c, Duration__c,Project__c, Actual_End_Date__c, Progress__c FROM Tasks__c WHERE Project__c:= {!contact.Project__c}";   //Records from dependency table
sforce.connection.sessionId = "{!$Api.Session_ID}"; 
var records = sforce.connection.query(query);
var records1 = records.getArray('records');
alert('Initial records:'+records1);
}
}

and
 
onclick="run('{!contact.Project__c}')"


Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S.  If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
 
This was selected as the best answer
Akanksha CullenAkanksha Cullen
Thanks for your reply Himanshu. Although, the code is still acting strange. I am not able to print the paramval value on the first call. So, bascially :
I click on the generate button, my alert box shows an empty value, my page loads, then again if I click on the button, it is showing me the paramval's value. 

Secondly, even after the second call, i get to see my paramval's value but my query is not working properly because of the WHERE clause in which it is checking with the paramval's value. 

I think it waits for my DOM to get the value first, then lets the script have the value. Could it be something like this?
Any ideas? 
Himanshu ParasharHimanshu Parashar
Hi Akanksha,

Your query will be like this. 
WHERE Project__c='{!contact.Project__c}'"

instead of
 
WHERE Project__c:= {!contact.Project__c}"

it should work with this.

Thanks,
Himanshu
Akanksha CullenAkanksha Cullen

But why does it work when I click button second time and not show me on the results on the first button click (when i load the page for the first time)? 
Himanshu ParasharHimanshu Parashar
It is because when page loads it doen't know the value of paramval. Put following code befor the closing </script> tag
 
run('{!contact.Project__c}');