JS code not executed
I am currently trying to call a JS script to export a chart from a surface chart component. The problem is that the base64str variable seems to be null, and the responsible script to fill that value is not called for whatever reason:
xhtml code:
<p:chart id="chart" type="line" widgetVar="chart" model="#{cont.lineModel}" style="height:550px;width:1800px">
<p:ajax event="itemSelect" listener="#{cont.itemSelect}" update="growl" />
</p:chart>
<p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
onclick="exportChart();" actionListener="#{cont.submittedBase64Str}"
/>
<h:inputHidden id="b64" value="#{cont.base64Str}" />
<script type="text/javascript">
function exportChart() {
img = chart.exportAsImage();
document.getElementById('hform:b64').value = img.src;
}
</script>
Controller:
public void submittedBase64Str(ActionEvent event){
// You probably want to have a more comprehensive check here.
// In this example I only use a simple check
if(base64Str.split(",").length > 1){
String encoded = base64Str.split(",")[1];
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded);
// Write to a .png file
try {
RenderedImage renderedImage = ImageIO.read(new ByteArrayInputStream(decoded));
ImageIO.write(renderedImage, "png", new File("D:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
thank
source to share
Change your attribute onclick
to onstart
.
<p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
onstart="exportChart();" actionListener="#{cont.submittedBase64Str}" />
This should call the JS function.
EDIT
In addition, you need to identify img
and chart
in your function.
source to share
chart
is a PrimeFaces JS widget. You define widgetVar
:
<p:chart ... widgetVar="chart"
And then you can get the chart object in your JS code like:
PF('chart')
You need to use the function PF
to get widgets with PrimeFaces 4.0.
As a side note, it is better to make the img
local variable instead of the global variable instead of the variable :
var img = chart.exportAsImage();
Now img
defined only in function scope.
source to share