[SalesForce] Passing a variable content from javascript to apex controller

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

Best Answer

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