Friday, June 4, 2010

Passing Objects in Javascript methods

I recently came across a requirement where I needed to call Javascript methods embedded in a flash module. The flash module was a chart from Fusion charts, and I wanted to perform certain client side actions when user clicked on these charts. Based on certain conditions and where the user clicked, I had to vary the number of parameters I pass to the javascript method.
I was looking for possible solutions and I figured out that the best way to achieve this was passing JSON objects as parameters. Here is how i did it:

link='javascript:jsMethod(%26apos;{\"param1\":\"param1Val\",\"param2\":\"param2Val\",\"param3\":\"param3Val\",\"param4\":\"param4Val\"}%26apos;)'

Note: I needed to escape single quote(') with %26apos; and double quotes(") with \". One can also use ' for single quote, and \x22 for double.

This approach of using JSON to pass variable number of parameters can be used in a variety of ways and keeps the method signature consistent.

This works for me, in case you have a better solution, please do write a comment.

No comments: