Passing Apex values to Javascript Code.

For the sake of completeness, and because I’ve received a large number of hits from the googled phrase ‘pass apex to javascript’, I thought it would be appropriate for me to write an article detailing the converse of an operation explain in a previous post.

Passing Apex values to JS is quite neat, and relatively simple. An example situation might be the need to grab data out of your Org, and display that data in some marvelous pictorial or graphical way(I particularly like the Google Visualization and Google Chart JS/AJAX APIs). There are some bordering-on-genius articles written concerning such implementations, but I thought I’d provide a foolproof(this is arguable), basic example of how you might display the value of an Apex variable using a JS alert.

Right, enough waffle(can I have mine with syrup please), let’s get a-coding. My FPBE(foolproof basic example) Apex class,

public class Fpbe{

public String myValue{get;set;}

public Fpbe(){

myValue = ‘What is that behind you!’;



And your Visualforce page would be,

<apex:page controller=”Fpbe”>

<script> alert(‘{!myValue}’); </script>


Easy peasy lemon squeezy.

As with most of my examples, this is a very basic example that a developer might use as a fundamental foundation for more complex application development.

7 thoughts on “Passing Apex values to Javascript Code.”

  1. Very nice. I recently figured out how to do this myself and was pleasantly surprised to find out how easy this is.

    I hope to have a post in the next month or so that shows bidirectional data passing with apex and javascript.

  2. I’ve done this many times, but what I really want to be able to do is figure out how to call a javascript function from my apex code. I also have real problems with javascript applied on re-rendered elements.

    • Do you mean directly from your apex code? Or on a page using and Apex method as a sort-of trigger? There is one trick I use that might work, depending on your answer:)


Leave a Comment