Friday, June 15, 2007

Passing arrays from JSF to Javascript

JSF can be a bit tricky and sometimes unfriendly when working with other tools especially Javascript functions that are not the simplest of implementations. One issue, that I have found very little documentation on the internet was how to pass arrays from JSF to a Javascript function.

Here's one way to accomplish passing an array to a Javscript function. This is limited by the amount of memory required to store a String, but in my case my upper bound of my array is well below the memory boundaries of the String.

1.) Create a String from an Array in your JSF page bean. This can also be set anywhere you JSF page can access the String value (i.e. session beans, etc). Use a delimiter between the elements of the array when converting the elements to a String to enable parsing later in this process.

2.) Reference the String created in step #1 wth an inputHidden. Here is an example...

<h:inputhidden id="bizStringAry" value="#{secure$BusinessEntry.businessStringAry}"></h:inputhidden>

3.) From the Javascript function reference the inputHidden field and place into a string. Use the Javascript split function on the String to remove the delimiters in step #1.

var bizname_array = document.getElementById('form1:bizStringAry').value
biz_fields_ary = bizname_array.split("?")

The biz_fields_ary is an actual Javascript array. You will need to reference the element(s) needed to process in your Javascript.

I hope this helps. Good luck!


Brijesh said...

Thanks, it worked. But why JSF EL could not handle this do you know any reason? I really wanted to know why JSF is so bad working with javascript.

I could not assign JSF tag with javascript it throws an error for ex.

var test = '{#bean.msg}'; will give exception but JSTL wont

any way thanks for the posting this solutuon

Anonymous said...

Is there still not any better way to do this in 2012?

Rob Castellow said...

Hi Anonymous. Good question! JSF 2.0 "should" work better with AJAX/Javascript since this was originally posted. There are some posts on how this works ... There is also jsf.js that seems to be fairly popular, and a possible solution to passing arrays to JS.

Thanks for the comment!

Anonymous said...

It works like a charm. Thanks for the help.

vanthong said...

It worked with my codes too! Now I can pass a list of images from my beans to JavaScript to draw on a canvas for manipulating one by one, pixel by pixel.
Thank you very much!