Release notes can contain some wonderful surprises in them, as Quinton mentioned – it’s always good to looking for some gems in there. Spring ‘11 is rolling out to general availability now, so you’ve either got your hands on it or should very soon. While we’ve talked a lot about some of the great new features with the REST API or Chatter, let’s look at one that is a little more under the radar at the moment: JavaScript Remoting.
First, you’ll need an globally scoped Apex class, with a static function defining the logic you want JavaScript to access. By adding the RemoteAction annotation, you’ll be letting Visualforce know it should wrap this logic in a JavaScript friendly way:
From there, associate the Visualforce to the class as a controller or extension, and Visualforce will include the ability to call the method from JavaScript. The framework works on asynchronous results, so after passing in your params, you can grab the result from a handler function. In this case, I’m taking my list of contacts and assigning it to a global array for use.
Then I can access the contacts and the fields I brought down with SOQL. In this example, I’ll use the returned array of contacts to browse for email and phone numbers. Here’s the complete, albiet quick and rough, Visualforce page:
And there you have it – with minimal overhead and effort, I have JavaScript powered by Apex in a client friendly manner. While the event object returned in the callback includes the type (so that you can determine if there was an error) and message (to get the proper error message from Apex), you can also poke around there and see which class and method you were calling from Apex if you need it. They are the action and method fields on the event object, respectively.
It’s pretty exciting stuff, and I can’t wait to see how it works with a certain library that rhymes with “jQuery”. Again though, remember this isn’t ready for the mass public right away as we’re still tinkering with it – but if you want to enable this on a Spring ’11 org, contact technical support or shoot me an email or catch me on twitter.