How to pass Arrays from backing bean to JavaScript to draw a chart using Chart.js in an Ajax call

984 Views Asked by At

I am using prime faces backing bean and Chart.js to draw a chart I am selecting a row in the data table . On selection of row updating the Canvas which has the Chart in it. I am getting the values on Selection method and building two arrays one for X axis and another for y-axis. How can i pass these arrays to JavaScript to render the chart . I tried Prime faces JSON array to pass to JavaScript. I could not get the values in JavaScrip.

Here is my sample code .xhtml code

    <p:dataTable id="myTbl" var="cars"  value="#{bean.value}"  rowKey="#{bean.carId}"  selection="#{bean.selectedCar}" selectionMode="single"  reflow="true" >            
           <p:ajax event="rowSelect" listener="#{bean.onRowSelect}" update=":chartForm"  oncomplete="drawChart();" /> 
   </p:dataTable>   




          <div class= "chart-container" > 
         <h:outputText id="outputid" value="#{bean.carId}" />              
         <canvas id="myChart"  ></canvas>     


         </div> 




 function drawChart(){   

   var carId = '#{bean.carId}';  

   alert (carId)

I am selecting a row from the above table. On selection I want to capture the id of the line , get data and display the chart.js chart on same page

here is my bean class In Bean Class

private String carId;

setter and getter methods

public void onRowSelect(SelectEvent event) { Cars car= (Cars) event.getObject();

this.carId  = car.Id ;

}

I got values into Primefaces JSON Array and passing into JavaScript .In JavaScript I am doing JSON.parse . Initially I got serialization error , so changed the bean to request scoped The problem is I am not getting any values into JavaScript I removed JSON Array and and just passing a String I can get the bean.property on xhtml page as mentioned in my code but not able to get into JavaScript Am i missing something

2

There are 2 best solutions below

1
On

Well, if you are concerned with the calling (and passing values) of JS function from bean, then you can call execute of RequestContext.getCurrentInstance() to directly invoke your scripting method from the bean, as following:

RequestContext.getCurrentInstance().execute("yourJSFunction('" + param1 + "');");

However, I think you will still be missing a trick of converting your JSONArray back to JSON object in JS, which you can do as following:

When passed from bean:

function yourJSFunction(coordinatesArray) {
    coordinatesArray = JSON.parse(coordinatesArray);
}

Or when using as a bean property:

var coordinatesArr = JSON.parse('#{yourBean.strProperty}');
3
On

you can try to use jsf expression language in javascript code

For example:

//<![CDATA[
var jsVar = #{managedBean.property}
//]]>