JavaScript Remoting for Apex operates in a very different paradigm from what you might be used to i.e. Visualforce pages have controllers and the two interact through action methods – where this might be a full form submission or some neat AJAX functionality. Remoting also calls controller methods but there is a gaping maw in terms of how the two work under the hood.
I’ve seen a few great articles on the syntax and example usage of JavaScript Remoting for Apex but when I started using it I came across a number domain differences that weren’t documented anywhere. Hopefully my list here will help you in the learning process. The best way to describe the new way of thinking is to examine the features set in contrast to “normal” Apex and Visualforce.
How JavaScript Remoting Differs
- Pass parameters naturally i.e. the call matches the method signature syntactically instead of requiring <apex:param/>.
- Action methods when called in “normal” Visualforce can only return NULL or a PageReference. Remoting allows you to return a wider range of data types, even objects and collections.
- Remoting methods have no access to the view state e.g. if a static variable is initialised to some value (outside the remoting method) a remoting method will see this as NULL unless it is re-initialised in that method! Conversely if a remoting method sets a state variable value the scope of that value is only within that method.
- It’s much faster. I’m building an application at the moment that is 95% backed by JS Remoting and when I show it to other developers they are struck dumb for at least 3 hours because of the speed.
- Neater debugging info in the browser console. Salesforce has done a great job of providing feedback directly to the browser’s console log.
- Each method call gets its own executional/transactional context i.e. fresh governor limits per call!
If I’ve missed anything please let me know and I’ll add it. Viva la knowledge crowdsourcing!
Reblogged this on Tquila.
Nice article.
I would like to add a Strategical flavour to that: when you decide to go Javascript remoting or to keep everything in the front-end by manipulating Json data only with a library such as JQuery:
– If you want a Session based/state based application, you might want to keep everything in the front-end. Indeed and as you mentionned, no View state for Javascript Remoting.
– In this case the key is to manipulate everything in Json and send the whole result to Apex only at the end for DML action.
– The Javascript remoting choice would be when you need direct DML action from the front-end, or SOQL request.
Of course nothing prevents you from mixing both, except the risk of making the application slitghly more difficult to debug.
Laurent
Very, very good advice.
I used this today to pass some values back to the controller for processing. It’s a simple implementation, but it’s blazing fast compared to actionFunction! Made for a much smoother UI experience.