I’ve written previously about how modern web app development increasingly favors client-side (i.e. in the browser) processing over server-side logic. In this “fat-client” architecture, the server is mostly responsible for providing an API that exposes backend data and the client is responsible for invoking the API, processing/massaging the data and rendering the appropriate view. This architecture is especially applicable to mobile web applications built using HTML5, CSS3 and JavaScript. For obvious reasons, JavaScript plays a critical and ever-growing role in this type of architecture. Modern MV* JavaScript frameworks like Backbone, Angular, Ember etc. help provide structure for such type of JavaScript-heavy web apps and if you haven’t done so already, I would highly encourage you to try atleast one of those frameworks.

Given that modern web apps are so reliant on JavaScript, I thought it would be useful to summarize the different ways that you can use JavaScript to interact with Salesforce data and logic on the backend. This is not meant to be an exhaustive review of any of these options – I have included links in each section for a deeper dive into the respective library/feature. Instead, this is meant to be a directory of sorts for web developers new to the Force.com platform. In addition to this list, please also review the basics of using JavaScript in Visualforce. That section of the Visualforce Developer Guide covers basics like how to include an external JavaScript library in a Visualforce page using <apex:includeScript>, accessing DOM elements in a Visualforce page etc. The JavaScript resource page on our developer portal is another great resource for all things JavaScript.

  1. apex:actionFunction: This standard Visualforce component lets you invoke an Apex controller action method directly from JavaScript code. In other words, you can invoke server-side logic (written in your Apex controller/extension) directly from JavaScript code on the Visualforce page.
    Code Snippet:

    <apex:actionFunction action="{!methodInApexController}" name="methodInJavascript" rerender="showstate">
    ....
    <script type="text/javascript">
         methodInJavascript();
    <script>

    For JavaScript hosted on: Visualforce pages.
    Pros: Simple and probably the easiest way to invoke Force.com server-side logic from JavaScript. Minimal JavaScript code required. Supports AJAX and the ability to specify a rerender target – i.e. you can refresh a portion of your Visualforce page based on the response from the server.
    Cons: The Apex controller/extension method cannot return data back to the invoking JavaScript code. The AJAX request includes the page view state, which can affect performance (depending on the complexity of the VF page).

  2. JavaScript Remoting: Somewhat similar to actionFunction, JavaScript Remoting lets you invoke methods in your Apex controller via JavaScript on the Visualforce page. However, in most cases, this is a more flexible and performant option when compared to actionFunction (watch this Dreamforce 2012 session for a more detailed comparison between the two).
    Code Snippet: 

    //Visualforce page code
    <script type="text/javascript">
         Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.MyController.getItemId}',
            objName,
            function(result, event){
                //process response here
            },
            {escape: true}
        );
    <script>
    //Apex Controller code
    @RemoteAction
    global static String getItemId(String objectName) { ... }

    For JavaScript hosted on: Visualforce pages.
    Pros: Supports parameters and return types in the Apex controller method (with automatic mapping between Apex and JavaScript types). Asynchronous processing via a callback. Unlike actionFunction, the AJAX request does not include the view state for the Visualforce page, thus resulting in a faster round-trip.
    Cons: When compared to actionFunction, JavaScript Remoting requires more code to be written.

  3. AJAX toolkit: The AJAX Toolkit allows you to invoke the Salesforce SOAP API via JavaScript on a Visualforce page. Unlike the previous two options, this approach only allows CRUD access to Salesforce data without the ability to invoke server-side (i.e. Apex) logic. The AJAX toolkit also has a very useful proxy function that allows your JavaScript to invoke non-Salesforce endpoints (which would otherwise be blocked by most browsers because of same origin policy restrictions).
    For JavaScript hosted on: Visualforce pages.
    Pros: Ability to access the richness of the SOAP API (including “higher-order” functions like convertLead, merge, getUpdated etc.) via simple JavaScript calls. The toolkit supports both sync and async invocation modes.
    Cons: Since the toolkit is a wrapper for the SOAP API, you consume API calls for every server-side interaction.
  4. JavaScript REST Toolkit (aka ForceTK) - This minimal toolkit allows JavaScript in Visualforce pages to call the Force.com REST API, providing an easy-to-use JavaScript wrapper. Due to the same origin policy, JavaScript running in Visualforce pages may not use XmlHttpRequest to directly invoke the REST API. The ForceTK toolkit works around the same origin restriction by using the AJAX Proxy to give full access to the REST API. You can also use ForceTK to invoke the REST API from JavaScript that is not hosted on the Force.com platform (requires the use of a simple PHP proxy) or from a PhoneGap/Cordova application.
    Code Snippet (for a Visualforce use case): 

    <apex:includeScript value="{!URLFOR($Resource.static, 'forcetk.js')}" />
    <script type="text/javascript">
        var client = new forcetk.Client();
        client.setSessionToken('{!$Api.Session_ID}');
        client.query("SELECT Name FROM Account LIMIT 1",
                     function(response){ ....});
    </script>

    For JavaScript hosted on: Any web page (Visualforce or otherwise) or PhoneGap application.
    Pros: Simple and very easy to use. Can be used from both within a Visualforce page and from an externally hosted web page. Since the toolkit wraps the REST API, all the advantages of using a lightweight HTTP/JSON based protocol like REST apply to this toolkit.
    Cons: Similar to the AJAX toolkit, you consume API calls when using ForceTK. The REST API does not support bulk DML operations and by extension, neither does ForceTK.

  5. RemoteTK – This variation of the ForceTK library provides a JavaScript abstraction very similar to the REST API, but without consuming API calls. It does so by implementing all the REST API resources (e.g. query, insert, update, upsert etc.) in an Apex class and then exposing them via JavaScript Remoting. By including a simple Visualforce Component in their page, developers can then make calls like client.describe(‘Account’, metadataCallback); in their JavaScript code.
    Code Snippet: 

    <c:RemoteTK />
    <script type="text/javascript">
        var client = new remotetk.Client();
        client.query("SELECT Name FROM Account LIMIT 1",
                     function(response){ ....});
    </script>

    For JavaScript hosted on: Visualforce pages.
    Pros: Unlike ForceTK, you don’t consume any API calls when using the RemoteTK library.
    Cons: Unlike ForceTK which only requires a simple import of the forcetk.js library, this option requires you to add an Apex Class and Component to your Org. This library also cannot be used from outside the Force.com Platform.

  6. Backbone.forceBackbone.js is one of the most popular JavaScript MVC frameworks. The Backbone.force library extends the Backbone framework (specifically the Backbone Model and Collection objects) and allows you to build a Backbone web application (in Visualforce, or externally hosted) that connects to a Salesforce backend.
    For JavaScript hosted on: Any web page (Visualforce or otherwise).
    Pros: Ability to build a Force.com web/mobile application using a modern MVC framework like Backbone.js.
    Cons: Requires knowledge of Backbone.js (which really isn’t a con!)
  7. nForceThis library is a Node.js wrapper for the Force.com REST API. Developed and maintained by Force.com community stalwart Kevin O’Hara, this Node.js NPM module allows access to Salesforce data from server-side JavaScript. In addition to the REST API, nForce also supports the Force.com Streaming API, whose real-time, push nature is a perfect compliment to a typical Node.js application.
    Code Snippet: 

    var nforce = require('nforce');
    var org = nforce.createConnection({....});
    org.authenticate({....});
    var acc = nforce.createSObject('Account');
    org.insert(acc, oauth, function(err, resp){
      if(!err) console.log('It worked!');
    });


    For JavaScript hosted on: Any Node.js application (hosted on say Heroku)
    Pros: Very easy to setup and use. Supports both the REST and Streaming API. Built-in support for session handling with express middleware.
    Cons: Requires knowledge of Node.js (again, not a con!)

 

If I’ve missed any other JavaScript toolkits/libraries that have been created by the Force.com community, please let me (and the community) know by adding a comment.
tagged , Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • http://twitter.com/greenstork Dave Manelski

    Jason Venable also put together this handy library, similar to RemoteTK: https://github.com/TehNrd/sObject-Remote

  • http://blog.shivanathd.com/ Shivanath D

    Thank you Sandeep, This is very helpful. Some of them are new to me, opens up a lot more possibilities

  • http://twitter.com/ApexAPI Apex

    Hi,

    You forgot the scripting toolkit (you can find the link on this page: http://wiki.developerforce.com/page/Tools )

    This tool allows you to develop console apps in javascript to access your org. It’s a layer wraping the ajax toolkit, using native Windows capabilities

  • http://twitter.com/osamanasir Osama Nasir

    Very nice post. I have a question, how do security settings apply if we use JS to query data from sf? In controllers we could use With/Without sharing to enforce security settings, how do we handle this using JS?

    • Anonymous

      Good question. It depends on which of the above outlined options you use. If your JS toolkit wraps one of the Force.com APIs (e.g. ForceTK, AJAX toolkit or nForce), then the security model is embedded in the respective API. In other words, the API will only return data that the logged in user is authorized to see in Salesforce (via the various security settings). If on the other hand you use something like JS Remoting or RemoteTK that use Apex in the backend, then the security model is the same as any other Apex class – namely with/without sharing.

  • http://twitter.com/kevino80 Kevin O’Hara

    Thanks for the nforce plug!

  • http://twitter.com/hemmeter Scott Hemmeter

    Great post to summarize the options for developers. There are great options. As an ISV with a native app, we started using actionFuncitons and have been moving to remoting. In terms of performance, remoting is improving things roughly 10x. There is an incredible amount over overhead with View State and actionFunction. If you are processing a good amount of data, I’d steer clear of actionFunctions. If you are keeping View State light and/or building pages for small record count query/manipulation, actionFunction is a great option.

    One trick to getting actionFunction return values is to have it re-render an outputPanel with JavaScript. We do this. We’ll have an outputPanel with 2 lines: one to capture a JSON object back from the controller and then a function called that passes in that object. We re-render that from the actionFunction and it runs as if the actionFunction returned values.

    • Anonymous

      Great trick for returning values with actionFunction. Thanks for sharing Scott!

  • http://free-12415f14c3a-124e539428a-12e57456865.sachin.cs5.force.com/SFBlogForce Sachin Agarwal

    I like the JavaScript Remoting & Rest Api in Salesforce. I am almost ready to deploy my first app on production within two weeks. To create it, i have done almost 98% coding in js & used jquery template to make my development easy. Now the best think in this, it is language independent and i can use any language which support jquery without doing any changes & effort.
    My app Video preview http://screencast.com/t/lwrxa4kWNdM6 http://screencast.com/t/a2dPz4g9pwd6

  • http://twitter.com/vg_force Vardhan Gupta

    Great Post!! Thanks for Sharing..

  • Tom Patros

    Thanks for the DF actionfunction vs. remoteaction session plug!

  • http://www.facebook.com/aishley.gera Aishley Gera

    Good Post. It is very useful for me because I always call a apex function via JS and It always take much time. But now I can improve my pages performance after this post.Thanks for this post.

  • Pramod Kumar

    Really very useful for developers.

  • http://twitter.com/zachelrath Zach McElrath

    Great post, Sandeep! One comment I would add is that it is really important for all of us developers, consultants, and ISV’s to make sure that, when we leverage external JavaScript libraries in our Salesforce pages, we do not inadvertently make life frustrating for other developers who will extend our code later by overwriting the JavaScript libraries that they are relying upon with conflicting versions (e.g. jQuery 1.3.2 overwriting jQuery 1.8.2). I wrote up a short post about ways to avoid this and protect yourself from the version-discrepancy problem: http://zachelrath.wordpress.com/2013/03/29/how-to-reliably-reference-external-javascript-libraries-in-visualforce-pages-or-components/

    • Anonymous

      Very nice link Zack. A must read for ISV developers on the Force.com platform. Thanks for sharing.

  • Sridhar Subramaniam

    Nice post Sandeep! I believe Backbone.force is using forcetk internally – tuns out to be API call again. Any one used it within VIsual force??

  • Harshit

    One trick to getting actionFunction return values is to have it re-render an outputPanel with JavaScript. We do this. We’ll have an outputPanel with 2 lines: one to capture a JSON object back from the controller and then a function called that passes in that object. We re-render that from the actionFunction and it runs as if the actionFunction returned values. This is a great trick for returning values with actionFunction which we are using but we are facing a problem wherein we are returning ‘true’ or ‘false’ value on the basis of whether the backend call is successful or some exception is thrown and accordingly we redirect to successful page or error page but since the outputPanel is rendered on page load as well so it is checking the value on page load and error page redirection happens since the value will always be false on page load. Is there any workaround for this or do I need to switch to Javascript Remoting…

  • Mobisoft Infotech

    Good Info. Thanks for the your effort. Appreciate it.

    http://mobisoftinfotech.com/services/cross-platform-mobile-development-usa/