Search code examples
javascriptjsfprimefacesmanaged-bean

Passing a parameter from javascript to managedbean


I have a variable in javascript in jsf page and I want to get this variable in my managed bean. have you any idea how I can do it?


Solution

  • This might not be the best solution, but I have done something similar in the past:

    In your managed bean (.java) you can access your front end elements by doing:

    Map<String, String> parameters = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
    
    for (Entry<String, String> formElement : parameters.entrySet()) {
            String elementName = formElement.getKey();
            if (elementName != null && //some other qualifier, for instance if the elementName starts with some pre-defined value) {
                String elementValue = formElement.getValue();
                //Set the variable in the backend
    
            }
    }
    

    And in your .js, you can create an element with for the variable you want to access from your managed bean:

    formElement = document.createElement('input');
    formElement.type = 'hidden';
    formElement.name = someName;
    formElement.id = someId;
    $(document.getElementById('spanId or divId')).append(formElement);