The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Passing Apex values to Javascript Code.

with 6 comments

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 Force.com 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>

</apex:page>

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.

Written by Wes

September 24, 2009 at 1:14 pm

6 Responses

Subscribe to comments with RSS.

  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.

    Jason

    September 24, 2009 at 4:49 pm

    • Good idea:) So you’ve come over to the JS side then?

      Wes

      September 24, 2009 at 8:35 pm

  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.

    d3developer

    September 24, 2009 at 7:44 pm

    • 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:)

      Wes

      September 24, 2009 at 8:37 pm

  3. Coming over to the JS side….. must resist google APIs.

    They are just too cool not to play with, but I still try to stick with 100% force.com as much as possible.

    Jason

    September 24, 2009 at 11:11 pm

  4. Whoops! I meant to add the comment above to the other post about passing values from Javascript to Apex. I’ve always known how to do this 😉

    Jason

    September 26, 2009 at 12:45 am


Leave a reply to Jason Cancel reply