Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6752027
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T12:59:48+00:00 2026-05-26T12:59:48+00:00

I am having trouble nailing down the best method for passing data from a

  • 0

I am having trouble nailing down the best method for passing data from a Java backing/managed bean to a jQuery/Javascript component such as Highcharts, so that my web app produces/displays data in a dynamic, real time way. I am pretty solid on my Java side of things but I have a pretty limited knowledge of JavaScript/jQuery which is obviously where I am falling down. So far as I have read, the best way is to Ajaxify a hidden field on my web app and pass a JSON object or string? in to it and then pass that value into my JS component.

Firstly this seems a bit labour intensive as I would have an Ajax call to update the JSON data and then a setInterval call to re-read the data into the JS component? I was hoping that I could pass the data straight into the JS component…

Either way could someone just firm up my knowledge and tell me a good tried and tested method, if different from above… Guides/Demo’s would also be massively appreciated!!

I also use Primeface’s 2.2.1 if this will affect a suggested methodology?

Cheers

Ally

UPDATE:

Code is below but I just want to describe what I am trying to achieve quickly: Effectively I am trying to implement a dynamic Highcharts chart, using a simple count++ function from my backing bean. Obviously further down the line I will be using a real-time feed to provide this data but at the moment I am just trying to get Highcharts to work based of changing information from my JSF backing bean.

Here is my simple count function and conversion to JSON (I am not sure if the JSON method is really necessary since only 1 value(int) is being passed, but I would like to retain this method as I am sure I will be using more extensively on other parts of the web app):

public class TestBean {

    private int output;

    public TestBean() {
        output = 1;
    }

    public int getOutput() {
        return output;
    }

    public void setOutput(int output) {
        this.output = output;
    }

    public void update() {
        setOutput(getOutput() + 1);
    }

    public void prepareChartDate() {
        // Produce you JSON string (I use Gson here)
        RequestContext reqCtx = RequestContext.getCurrentInstance();
        reqCtx.addCallbackParam("chartData", new Gson().toJson(output));
    }
}

Highcharts External JS File, again its worth noting that I have maintained the series function at the bottom of the chart to build/populate the graph before I start appending values obtained from the JSF Beans:

Highcharts.setOptions({
    global: {
        useUTC: false
    }
});

var chart;
$(document).ready(function() {
    chart = new Highcharts.Chart({
        chart: {
            backgroundColor: "#F8F0DB",
            renderTo: 'containerHigh',
            defaultSeriesType: 'area',
            margin: 10,
            marginLeft:30,
            marginBottom:17,
            zoomType: 'y',
            events: {
                load: updateChartData
            }
        },
        title: {
            text: 'Feed Flow Rate '

        },
        xAxis: {
            type: 'datetime',
            tickPixelInterval: 150
        },
        yAxis: {
            title: {
                text: ''
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            formatter: function() {
                return '<b>'+ this.series.name +'</b><br/>'+
                Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+ 
                Highcharts.numberFormat(this.y, 2);
            }
        },
        legend: {
            enabled: false
        },
        exporting: {
            enabled: false
        },
        plotOptions: {
            area: {
                fillColor: {
                    linearGradient: [0, 0, 0, 100],
                    stops: [
                    [0, Highcharts.getOptions().colors[0]],
                    [1, 'rgba(2,0,0,0)']
                    ]
                },
                lineWidth: 1,
                marker: {
                    enabled: false,
                    states: {
                        hover: {
                            enabled: true,
                            radius: 5
                        }
                    }
                },
                shadow: false,
                states: {
                    hover: {
                        lineWidth: 1                        
                    }
                }
            }
        },
        series: [{
            name: 'Random data',
            data: (function() {
                // generate an array of random data
                var data = [],
                time = (new Date()).getTime(),
                i;

                for (i = -19; i <= 0; i++) {
                    data.push({
                        x: time + i * 10000,
                        y: 50 * Math.random()
                    });
                }
                return data;
            })()
        }]
    });        
}); 

And the inline JS Function held on my XHTML page:

This works:

 function updateChartData(xhr, status, args) { 
    var series = this.series[0];
    setInterval(function() {            
        var x = (new Date()).getTime()
        y = 50 * Math.random();
        series.addPoint([x, y], true, true);   

    }, 1000)       
//parse it, process it and load it into the chart
}

but when I try to pass my bean value:

 function updateChartData(xhr, status, args) { 
    var jsonString = args.chartData
    var series = this.series[0];

    setInterval(function() {            
        var x = (new Date()).getTime()
        y = jsonString 
        series.addPoint([x, y], true, true);   

    }, 1000)       
//parse it, process it and load it into the chart
}

That doesnt work…

Also I’ve been trying both remoteCommand and Poll to get the chart to work, neither of which I have been successful with:

 <h:form>                       
                    <p:commandButton value="update" action="#{testBean.update}" update="beanvalue"/> 

                    <h:outputText value="#{testBean.output}" id="beanvalue"/> <br />
                    <h:outputText value="#{testBean.output}" id="chartValue"/> <br />

                    <p:commandButton value="Load" type="button" onclick="fetchChartData();"/>
                    <p:remoteCommand name="fetchChartData"
                                     action="#{testBean.prepareChartDate()}"
                                     oncomplete="updateChartTest(xhr, status, args);"/>            
                </h:form>

As I’ve said before Bhesh, your help is massively appreciated and anymore would be great!

Cheers

Ally

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T12:59:48+00:00Added an answer on May 26, 2026 at 12:59 pm

    If you are using PrimeFaces 2.2.1 then it should be pretty easy to acheive what you are trying to do.

    PF has a component p:remoteCommand with which you can Ajaxicaly invoke a managed-bean method.

    <h:form id="frmIrsChartData">
        <p:remoteCommand name="fetchChartData"
                         action="#{chartManagedBean.prepareChartData()}"
                         oncomplete="updateChartData(xhr, status, args);"/>
    </h:form>
    

    And in the method prepareChartData() you produce your JSON string and use RequestContext provided by PF to send it back to client:

    public void prepareChartDate() {
        // Produce you JSON string (I use Gson here)
        RequestContext reqCtx = RequestContext.getCurrentInstance();        
        reqCtx.addCallbackParam("chartData", jsonString);
    }
    

    And in the Javascript callback function updateChartData(xhr, status, args) you can process the JSON response and load into the chart:

    function updateChartData(xhr, status, args) {
        var jsonResponse = args.chartData;
        //parse it, process it and load it into the chart
    }
    

    And to periodically update the chart just use the Javascript setInterval or setTimeout and pass the name of the remoteCommand which is actually a Javascript function.

    setInterval("fetchChartData()", 5000);
    

    That’s how I do it.

    PF also has another component p:poll which makes it easier to implement live charts.

    Update:

    You got it wrong. On

    What you need to do is on document-ready render the chart first and then start you poll.

    $(document).ready(function() {
        chart = new Highcharts.Chart({
            //....
        });
        // start your poll here
    });
    

    The p:poll callback function updateChartData(xhr, status, args) needs be global so that the poll can call it on oncomplete event.

    function updateChartData(xhr, status, args) {
        var jsonResponse = args.chartData;
        //parse it, process it and load it into the chart
        //you will load data into the same chart created in document-ready
    }
    

    And when you are using poll you do not need the setTimeout or setInterval.

    Update 2:

    First of all, in updateChartData function you are supposed to update the chart that you created:

    function updateChartData(xhr, status, args) { 
        var series = chart.series[0]; // <--- no more this instead global variable "chart"
        var newData = args.chartData;
        var x = (new Date()).getTime()
        var y = eval('(' + newData + ')');
        series.addPoint([x, y], true, true);
    }
    

    Next, updateChartData is callback function so don’t call it yourself, it is called by the remote-command every time the request is complete.

    And, give the remote-command a separate form of it’s own:

    <h:form>
        <p:remoteCommand name="fetchChartData"
                         action="#{testBean.prepareChartDate()}"
                         oncomplete="updateChartData(xhr, status, args);"/>
    </h:form>
    

    Note in oncomplete="updateChartTest(xhr, status, args);" in your code the callback function should be updateChartTest instead of updateChartTest.

    Trigger the ajaxical polling after the chart is done loading:

    events: {
           load: function() {
               setInterval("fetchChartData()", 5000); //update the chart every 5 seconds               
           }
    }
    

    For testing only, trying returning a random value from you managed-bean:

    public void prepareChartDate() {
        // Produce you JSON string (I use Gson here)
        RequestContext reqCtx = RequestContext.getCurrentInstance();
        reqCtx.addCallbackParam("chartData", new Random().nextInt(500));
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Having trouble getting the javascript alert to display from my code behind. c# -
Im having trouble reading from a CSV file final String DELIMITER = ,; Scanner
Having trouble with AR 2.3.5, e.g.: users = User.all( :select => u.id, c.user_id, :from
Having trouble getting my JQuery POST to be accepted by the WCF Service. Here's
Having trouble getting the oauth access token and secret exchanged from the request tokens
Having trouble getting my POST arrays to show all checkbox values from my form.
im having trouble extracting the trend name and search query from the json response
Having trouble with the db.alter command when changing a date field from null=True and
Having trouble here and not quite sure how to do it. I've attempted jQuery
Having trouble inheriting from a template class. Looks something like this: template<typename type> class

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.