[SalesForce] Passing values from javascript to controller

I am setting a value of hidden field in javascript which is fired on button click but when controller function is called hidden field value is not passed along as I expected.

Visual Force Page:

<script type="text/javascript">         
    function getName() {
        var fileInput = $('#idFileUpload');
        var fileName = fileInput.get(0).files[0].name;
        $('#hdnDocName').val(fileName);
        alert($('#hdnDocName').val());
        if ($('#hdnDocName').val() != '') {
            return true;
        }
        else
        {
            return false;
        }
    }
</script>
<apex:form id="upload-form">
    <apex:pageMessages />
    <br/>
    <apex:outputPanel rendered="{!accountID != ''}">
        <input id="hdnDocName" value="{!filename}" type="hidden" />
        Please select image: 
        <input id="idFileUpload" data-max-size="2097152" type="file" name="uploadfile" value="{!doc.body}" accept="image/x-png, image/gif, image/jpeg, image/jpg" />
        <br/><br/>
        <apex:commandButton value="Upload" onClick="if (getName() === false) { return false; }" action="{!SaveAttachment}"/>    
    </apex:outputPanel>
    <apex:outputPanel rendered="{!accountID == ''}">
        No valid account selected
    </apex:outputPanel>
</apex:form>

Controller:

public String filename { get; set; }
public Pagereference SaveAttachment()
{   
    System.Debug(filename); 
    return null;
}

debug statement returns null. How do I pass values?

Best Answer

You are binding the filename field into the page when it is generated but you are not taking advantage of Visualforce's automatic binding of values back into the controller. To do so in this case you will need to use apex:inputHidden:

<apex:inputHidden id="hdnDocName" value="{!filename}"/>

As the id value gets prefixed in the generated HTML you can use jQuery's ends with selector syntax to match the element:

$("[id$='hdnDocName']").val(fileName);