0

I want to load JavaScript function on startup with window.onload and that function would pass its parameters to a Managed Bean.

Without a commandButton.

JS:

window.onload = function getVars() {
    // ...
    var x = locationInfo.lng; 
    var y = locationInfo.lat;

    document.getElementById("formId:x").value = x;
    document.getElementById("formId:y").value = y;
}

XHTML:

<h:form id="formId">
    <h:inputHidden id="x" value="#{bean.x}" />
    <h:inputHidden id="y" value="#{bean.y}" />
</h:form>

Managed Bean is a regular managed bean with its getters and setters.

This code is not working without clicking a commandButton.

Is there way to load parameters with JavaScript and pass it to JSF?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
MertTheGreat
  • 500
  • 1
  • 7
  • 20
  • Far away from a perfect duplicate but the answer solves the 'user has to click a button' issue. – Selaron May 16 '19 at 08:08
  • It is marked as duplicate but I do not think it is. First of all I am trying to do it without clicking a button. I do not think the title of the other question is clear enough. I did my search and it should be far below. – MertTheGreat May 16 '19 at 10:07
  • It's not the title makeing it a duplicate. The answer to the other question is also answering your question how to submit a JSF form from javascript without requiring the user to click a button. Don't take toe word "duplicate" too strictly. – Selaron May 16 '19 at 12:21

1 Answers1

1

You can do it with remoteCommand.

<p:remoteCommand name="sendArgs" actionListener="#{mybean.rcvArgs()}" partialSubmit="true" process="@this"/>

and do a javascript call

sendArgs([
            {name: 'xval', value: locationInfo.lng},
            {name: 'yval', value: locationInfo.lat}
        ]);

in mybean you have to take the arguments from the parameter list

public void rcvArgs() {
    Map<String, String> pmap;
    pmap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

    String xval = pmap.get("xval");
    String yval = pmap.get("yval");
Holger
  • 899
  • 2
  • 7
  • 12