+ Start a Discussion
Shohrat MuhamovShohrat Muhamov 

Pass value from JavaScript to Controller

I need to pass user input from javascript in visualforce button to Apex controller, to add it to field. Can anyone hep me with it please?
Raj VakatiRaj Vakati
Refer this link 


For additional info 

Deepali KulshresthaDeepali Kulshrestha
Hi Shohrat,

You can pass the value from javascript to controler by action function:

Please have a look at this code:

<apex:page showHeader="true" sidebar="true" controller="SampleController">
    <script type="text/javascript">
           window.onload = function(){
               //this is calling the apex:actionFunction below with the same name when the page loads
               console.log('setUserLocation called');

    <apex:form >
        <!-- this action function can be called from javascript -->
        <apex:actionFunction name="setUserLocation" action="{!setUserLocationInApex}" rerender="">
            <apex:param name="userLocation" value="" />
For more infomation you can also refer to this link:-

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
Shohrat MuhamovShohrat Muhamov
Hello Deepali,

I have tried your method before, but it didn't work for me. I am using promt  function from java script to get user input.

Best Regards,
Shohrat Muhamov
Ajay K DubediAjay K Dubedi
Hi Shohrat,
You can use remoting action to pass data from javascript to Apex controller. Please try the below code and let me know if this works for you.
Apax Page:
<apex:page controller="RemoteControllerExample">
    <apex:slds />
    <div class="slds-grid slds-gutters">
        <div class="slds-col">
            <span>  <input type="text" name="name" class="slds-input" id="name"/></span>
        <div class="slds-col">
            <span><input type="text" name="billingAdd" class="slds-input" id="billingAdd"/></span>
        <div class="slds-col">
            <span><button class="slds-button slds-button_brand" onclick="fun();">Save</button></span>
    function fun() {
        var name = document.getElementById("name").value;
        var billing_add = document.getElementById("billingAdd").value;

Controller :

public class RemoteControllerExample {
    public static Account RemoteControllerExampleMethod(String name,String billing_city) {
        Account accObj = new Account();
        accObj.Name = name;
        accObj.BillingCity = billing_city;
        insert accObj;
        return accObj;

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Ajay Dubedi