0

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..

3
  • you want to get myMethod return value in JS.?
    – Ratan Paul
    Commented Nov 25, 2015 at 12:26
  • @Ratan no I want to get passThisValue() return value in apex
    – Joey Pablo
    Commented Nov 25, 2015 at 12:27
  • Pls add your passThisValue function
    – Ratan Paul
    Commented Nov 25, 2015 at 12:29

1 Answer 1

2
<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.

2
  • Thank you ! I don't know why I complicated it x)
    – Joey Pablo
    Commented Nov 25, 2015 at 12:54
  • No problem @JoeyPablo
    – Ratan Paul
    Commented Nov 25, 2015 at 13:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .