How do I pass JSF managed bean properties to a JavaScript function?
This is not exactly "passing" of JSF variables. This is just printing JSF variables as if they are JavaScript variables/values. You know, JSF and JS do not run in sync at all. JSF runs in webserver and produces HTML/CSS/JS code which in turn runs in webbrowser once arrived over there.
Your concrete problem is most likely caused because you wrote JSF code in such way that it generates invalid JS syntax. An easy way to verify that is by just checking the JSF-generated HTML output which you can find by rightclick, View Source in browser, and by checking if you don't see any syntax error reports in the JS console in browser which you can find by pressing F12 in Chrome/IE9+/Firefox23+.
Imagine that #{entity.key}
here
<a onclick="actualizaMenu(#{entity.key})">#{entity.nombre}</a>
prints a Java string variable like "foo"
, then the generated HTML would look like<a onclick="actualizaMenu(foo)">some name</a>
But hey, look, that represents a JavaScript variable named foo
, not a JS string value! So if you actually want to ultimately end up as<a onclick="actualizaMenu('foo')">some name</a>
then you should instruct JSF to generate exactly that HTML:<a onclick="actualizaMenu('#{entity.key}')">#{entity.nombre}</a>
Beware of special characters in the JSF variable though. You can use OmniFaces of:escapeJS()
function for that.Unrelated to the concrete problem, the concrete implementation of
actualizaMenu()
makes no sense. You seem to be attempting to set a bean property. You should not use JS for that, but a <h:commandLink>
instead.<h:commandLink value="#{entity.nombre}" action="#{linkedMenu.setKey(entity.key)}" />
Nest if necessary a <f:ajax>
to make it asynchronous. How to pass backing bean value to JavaScript?
To the point, you need to understand that JSF merely produces HTML code and that JS is part of HTML. So all you need to do is to write JSF/EL code accordingly that it produces valid HTML/JS code. Indeed, using EL to inline bean properties in the generated JavaScript code like as in your attempt is one of the right ways.
Assuming that this is indeed the real code, you however made some syntax mistakes. The onClick
attribute is invalid. It must be in all lowercase. Otherwise JSF simply won't render the attribute at all.
<h:commandLink value="link" onclick="showNoQueryPrompt(#{enquiry.noQuery})" />
JavaScript has no notion of strong typing. The Boolean
type in function argument is invalid. Remove it. Otherwise you will face a nice JS syntax error (in browser's JS console).function showNoQueryPrompt(showPrompt) {
if (showPrompt) {
alert('No query');
}
}
Note that I expect that you understand that this runs before commandlink's own action
is been invoked (you should now have understood; JSF generates HTML; rightclick page in browser and View Source to see it yourself). But you didn't cover that in your concrete question (even more, you didn't describe the concrete problem with the given code in the question at all), so I can't give an detailed answer on that. How to pass a value inside javascript to managed bean property without using hidden tags in JSF?
You can create a json object with name value pair like in a map and send them as a request parameters. You can have a p:remoteCommand
which could be called from your javascript function like below
function sendParams() {
passToJSFManagedBean ([ {
name : 'sno',
value : 1
},
{
name : 'name',
value : srikanth
}
]);
}
The above passToJSFManagedBean
should be a name of a remote command function like below <p:remoteCommand name="passToJSFManagedBean" id="passToJSFManagedBeancmd"
action="#{myBean.getParams}"
process="@this" />
You can access the params passed in your managed bean action public void getParams() {
String sno= FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
.get("sno");
//same way you can get name
}
Hope this helps How to pass JavaScript variables as parameters to JSF action method?
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? How to Pass JSF Bean data to JavaScript Function?
The problem is that the arguments of the oncomplete
-function are only updated when the view is entered. The arguments are not automatically updated when the value of the properties on the bean have changed. So as chartController.chartData
is initially not instanciated it is null
when the page is rendered and remains null
until you manually refresh the whole page.
To fix this issue I would recommend you to use the Primefaces RequestContext and add the chartData
everytime loadChartData
is called as a callback param.
I.e. add the following to the and of loadChartData
:
public void loadChartData() {
...
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("chartData", chartData);
context.addCallbackParam("categories", categories);
}
And in the UI define the p:poll
as follows:<p:poll interval="3" listener="#{chartController.loadChartData}"
oncomplete="renderChart('container','area','Sample Chart', args.chartData, args.categories);"
id="chartvalue_btn" update="textID" />
If this is no option for you, because you are using loadChartData
anywhere else, wrap the call of loadChartData
with the addCallbackParam
stuff in another method and specify this method as listener of the p:poll
. how to get managed bean property value inside javascript
You can like this:
<h:inputText id="propertyId" value="#{myBean.property}" style="display:none"/>
and access it like this (note that if its inside a form you might need to add the form prefix)alert($('#propertyId').val()); // or alert($('#myFormId\\:propertyId').val());
How to call managed bean methods with parameters via JavaScript
Just to add to Kishor's (halfway) answer, you need to have a to-be-updated component in your view (popup window as you call it) and ajax-update it after the request has been successfully completed.
You can use remote command to send the AJAX request with an extra parameter attached and ajax-update the JSF component responsible to be a popup window. Like so (for PrimeFaces 3.x):
<p:remoteCommand name="myRemote" actionListener="#{myBean.listen}"
update="dialog" oncomplete="dlg.show()" />
...
<div onclick="myremote([{name:'poi_id', value:poi_id}]);">...</div>
...
<p:dialog id="dialog" widgetVar="dlg">
<h:outputText value="#{myBean.address}" />
...(display other information)
</p:dialog>
withString address;
public void listen(){
String poi_id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("poi_id");
address = getAddress(poi_id);
}
The alternative to using a remote command is to have a hidden form with a hidden input that will be used to transmit the parameter to the backing bean, that could be separated from other beans to handle the retrieval of necessary information based on your poi_id
:<h:form id="poi-form" styleClass="invisible">
<h:inputHidden id="poi" value="#{poiBean.poi}" />
<p:commandButton id="info" action="#{poiBean.info}"
update="dialog" oncomplete="dlg.show()" />
</h:form>
<div onclick="document.getElementById('poi-form:poi').value = poi_id;
document.getElementById('poi-form:info').click();">...</div>
...
<p:dialog id="dialog" widgetVar="dlg">
<h:outputText value="#{poiBean.address}" />
...(display other information)
</p:dialog>
with@ManagedBean
@RequestScoped
public class PoiBean {
private String poi;//getter+setter
private String address;//getter
//other properties
public void listen(){
address = getAddress(poi);
//other properties
}
}
Calling Managed Bean Method From JavaScript
You have a few options. If you are using JSF 2.0 you can build a composite component around these area tags.
The easiest way however would be to invoke a hidden JSF input button.
<h:commandButton id="hdnBtn" actionListener="#{personBean.method}" style="display: none;" />
This will render as an input
HTML element on the page that you can access from Javascript and invoke its click
event.onclick="jQuery('#form:hdnBtn').click();"
Related Topics
JavaScript String and Number Conversion
How to Load All Files in a Directory Using Webpack Without Require Statements
Why Do People Put Code Like "Throw 1; <Dont Be Evil>" and "For(;;);" in Front of JSON Responses
Splicing a JavaScript Array from Within the Callback Passed to Foreach
JavaScript Request Fullscreen Is Unreliable
What Exactly Can Cause an "Hierarchy_Request_Err: Dom Exception 3"-Error
Convert CSV Data into JSON Format Using JavaScript
Using Filesystem in Node.Js with Async/Await
What Is the JavaScript Mime Type for the Type Attribute of a Script Tag
Can Promises Have Multiple Arguments to Onfulfilled
Remove Whitespace and Line Breaks Between HTML Elements Using Jquery
Viewing All the Timeouts/Intervals in JavaScript
Access 'Data-' Attribute Without Jquery
Obtain Smallest Value from Array in JavaScript
Angularjs "Controller As" or "$Scope"
Converting a Buffer into a Readablestream in Node.Js