Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'd like to know if there's a way to pass a variable from javascript to apex by calling a js function that returns some var ? here's the example code the function that returns that var is called passThisValue();

public class myClass {
    public String myString {get; set;}

    public myClass(){
        myString = '';
    }

    public PageReference myMethod(){
        System.debug('myString: ' + myString);
        return null;
    }
}

VisualForce page:

<script>
function setVar(param){
    jQuery('[id$=myHiddenField]').val(param);
    passStringToController();
}
</script>

<apex:inputHidden value="{!myString}" id="myHiddenField"/>

<apex:actionFunction name="passStringToController" action="{!myMethod}" rerender="myHiddenField"/>

<apex:commandButton value="Test me" onclick="setVar(passThisValue()); return false;" />

I've tried with setVar(passThisValue()); but setVar doesn't get what my function returns..

share|improve this question
    
you want to get myMethod return value in JS.? – Ratan Nov 25 '15 at 12:26
    
@Ratan no I want to get passThisValue() return value in apex – Joey Pablo Nov 25 '15 at 12:27
    
Pls add your passThisValue function – Ratan Nov 25 '15 at 12:29
up vote 1 down vote accepted
<script>
function setVar(param){
    passStringToController(param);
}
</script>

<apex:inputHidden value="{!myString}" id="myHiddenField"/>

<apex:actionFunction name="passStringToController" action="{!myMethod}" rerender="myHiddenField">
    <apex:param name="strParam" value="" assignTo="{!myString}"/>
</apex:actionFunction>

<apex:commandButton value="Test me" onclick="setVar(passThisValue()); return false;" />

no need to assign the value to inputHidden. If you get the value in JS and pass in action function else

<apex:actionFunction name="passStringToController" action="{!myMethod}" rerender="myHiddenField">
  <apex:param name="strParam" value="" assignTo="{!myString}"/>
</apex:actionFunction>

<apex:commandButton value="Test me" onclick="passStringToController(passThisValue()); return false;" />

Directly call action function and pass the value.

share|improve this answer
    
Thank you ! I don't know why I complicated it x) – Joey Pablo Nov 25 '15 at 12:54
    
No problem @JoeyPablo – Ratan Nov 25 '15 at 13:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.