5

I want to send my arraylist from managedBean to javascript code,

my bean is here:

public void getDataAsJson(){
    String [] dizi={"Tokyo","Jakarta","New York","Seoul",
              "Manila","Mumbai","Sao Paulo","Mexico City",
              "Dehli","Osaka","Cairo","Kolkata",
              "Los Angeles","Shanghai","Moscow","Beijing",
              "Buenos Aires","Guangzhou","Shenzhen","Istanbul"};

    Random rnd =new Random();

    JSONObject obj= new JSONObject();
    for (int i = 0; i < dizi.length; i++) 
        obj.put(dizi[i], new Integer(rnd.nextInt(80)));
}

my javascript code is here in xhtml page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
<!--

$(function () {

    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                zoomType: 'xy'
            },
            title: {
                text: 'avarage'
            },
            subtitle: {
                text: ''
            },
            xAxis: [{
                gridLineWidth: 0.5,
                categories: [// here is my city names which come from mybean]
            }],
            yAxis: [{ // Primary yAxis
                labels: {
                    formatter: function() {
                        return this.value;
                    },
                    style: {
                        color: '#89A54E'
                    }
                },
                title: {
                    text: 'avarage',
                    style: {
                        color: '#89A54E'
                    }
                }
            }],

            series: [{
                name: 'avarage',
                color: '#89A54E',
                type: 'spline',
                data: [// // here is my city's avarage which come from mybean],
                       labels: {
                        rotation: -90,
                        align: 'right',
                        style: {
                            fontSize: '13px',
                            fontFamily: 'Verdana, sans-serif'
                        }
                    }
            }]
        });
    });
});
//-->
</script>

here is my body in xhtml page:

<body>   
  <script src="http://code.highcharts.com/highcharts.js"></script>
  <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body> 
4
  • stackoverflow.com/editing-help#code Commented Mar 18, 2013 at 14:10
  • So, what have you tried after this? I don't see any JSF code to attempt calling your getDataAsJson method. Commented Mar 18, 2013 at 14:25
  • stackoverflow.com/a/9886212/617373 Commented Mar 18, 2013 at 14:38
  • Just in case you want a little something extra and see a quick hint as to how can you send and receive data between JS and your ManagedBean: stackoverflow.com/a/15341284 Commented Mar 18, 2013 at 14:42

2 Answers 2

12

You need to understand that JSF is in the context of this question merely a HTML/JS code generator.

You just need to let JSF print the desired data in such way that it ends up in syntactically valid JS code.

categories: #{bean.dataAsJson}

Wherein getDataAsJson() returns a String representing the desired JSON code. E.g. basically:

public String getDataAsJson() {
    return "['foo', 'bar', 'baz']";
}

To verify the result, rightclick page in browser and do View Source.

categories: ['foo', 'bar', 'baz']
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget to protect against XSS attacks (further reading).
-1

Send data to javascript routine via JSF Bean is not good idea but my solution is working with java web service or JAX-RS. The java web service contains 2 classes, JaxRsActivator and resources class. Here is source code of JaxRsActivator:

package service;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class JaxRsActivator extends Application {
}

Here is source code of resource class.

package service;

import static javax.ws.rs.core.MediaType.TEXT_PLAIN;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/resource")
@Produces(TEXT_PLAIN)
public class resource {

@GET
@Path("cities")
public String dizi() {
    String s = "{\"Tokyo\",\"Jakarta\",\"New York\",\"Seoul\",\r\n" + 
            "\"Manila\",\"Mumbai\",\"Sao Paulo\",\"Mexico City\",\r\n" + 
            "\"Dehli\",\"Osaka\",\"Cairo\",\"Kolkata\",\r\n" + 
            "\"Los Angeles\",\"Shanghai\",\"Moscow\",\"Beijing\",\r\n" + 
            "\"Buenos Aires\",\"Guangzhou\",\"Shenzhen\",\"Istanbul\"};\r\n";
    return s;
}

}

Now a modification in our JavaScript. Make your anonymous function for generating chart a named function e.g.: generateChart(CityData) and modify line with data: becomes data: CityData, Your JavaScript start with:

$(function () {
    var xhr = new XMLHttpRequest();
    // replace the dots
    var url = "http://localhost:8080/........../resource/cities";           

    xhr.onreadystatechange = function() {
    // Check if fetch request is done
     if (xhr.readyState == 4 && xhr.status == 200) { 
        console.log(xhr.responseText);
        // Parse the JSON string
        var jsonData = eval(xhr.responseText);
        generateChart(jsonData);
        }
    };

    // Do the HTTP call using the url variable we specified above
    xhr.open("GET", url, true);
    xhr.send();

function generateChart(CityData) {
    // put your code for generating your chart
    // modify line
    data: CityData
}

// End of JavaScript

Put also this JavaScript on the end of your JSF page. After the page loading start the JavaScript with data loading and after the data loading start the chart generation.

succes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.