Integrate salesforce with Jquery/JavaScript

Salesforce Feb 28, 2015

I had faced many issues while integrating JavaScript to ApexRest(Salesforce) directly and want to share my experience and code with all. Here, we are trying to integrate JavaScript(client-side) and Salesforce without involving any other server/middle-ware. In most of solutions, they prefer to hit own server or middle-ware through JavaScript and then server/middleware will integrate with Salesforce. We will integrate it without any middle-ware

First of all , it's very important to understand how request/response headers work otherwise it is very difficult to debug issues. Secondly, we usually see 'cross domain error' while implementing. We will discuss its solution too.

Lets take few examples:

  1. We have a scenario wherein we need to make a hit to salesforce from a page and then display results in UI. In this example, we will be using Jquery and ApexRest in solution.

    Problem : Above ajax request will hit salesforce but will get cross domain error

    How to remove this error?

    We need to implement CORS. This is mechanism to allow many resources (e.g., fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain the resource originated from. Basically , we need to add few headers at server end (Salesforce) to allow JavaScripts to integrate properly.

    Upgraded code:

    Solution : 'Access-Control-Allow-Origin' header will allow domains to hit salesforce apex rest. we can use '*' to allow all domains or domain name for specific domains.

  2. In case of POST request , we need to keep above solution in mind for cross domain error plus playing around with headers to pass body correctly

    Problem : When we hit jquery hit salesforce with jsonData, salesforce won't get body in request. This is because Jquery sets 'application/x-www-form-urlencoded' as Content-Type by default and this header won't send body correctly.

    Solution : Disable the jquery to add default type and send body as it is. This an be done by adding attributes in ajax request

    Upgraded Ajax request:

    contentType: false & processData: false will not add default Content-Type and hence will not process data and will send as it is.

Hope these solutions will help!!

Related Blog : Integrate salesforce with JSONP

Related Tags:

Salesforce   JavaScript