Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  72] [ 2]  / answers: 1 / hits: 41464  / 9 Years ago, wed, february 18, 2015, 12:00:00

I'm preparing some variables in JavaScript (in my specific case, I'd like to get GPS location):



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


I'd like to send them to my managed bean via the below command button:



<h:commandButton value=submit onclick=getVars() action=#{bean.submit(x,y)} />


public void submit(int x, int y) {
// ...
}


How can I send x and y variables from JavaScript to JSF managed bean action method?


More From » jsf

 Answers
28

Let JS set them as hidden input values in the same form.



<h:form id=formId>
<h:inputHidden id=x value=#{bean.x} />
<h:inputHidden id=y value=#{bean.y} />
<h:commandButton value=submit onclick=getVars() action=#{bean.submit} />
</h:form>




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

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


The command button action method could just access them as bean properties the usual way.



private int x;
private int y;

public void submit() {
System.out.println(x: + x);
System.out.println(y: + y);
// ...
}

// Getters+setters.


An alternative is to use OmniFaces <o:commandScript> or PrimeFaces <p:remoteCommand> instead of <h:commandButton>. See also a.o. How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?


[#67771] Tuesday, February 17, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhett

Total Points: 671
Total Questions: 100
Total Answers: 102

Location: Hong Kong
Member since Tue, Oct 19, 2021
3 Years ago
;