Integrating Salesforce with Javascript/Jquery (JSONP)

Salesforce Feb 28, 2015

In my previous blog 'Integrate Salesforce with any HTML page with Jquery/Javascript ' , I have tried to integrate Salesforce with JavaScript/Jquery by playing around with headers to implement CORS for cross domain . I have found one more way to directly get data from Salesforce without much effort.Using JSONP can make it easier. Lets discuss some background about JSONP.

What is JSONP?

JSONP or JSON with padding is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on "script" tags. For JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted result.

Check this wiki link for more info about JSONP.

How JSONP help in integration with Salesforce?

As discussed above, server should response with JSONP format and that will be understood by JSONP Supported Client(Here Javascript) and will perform further process. In our case server is Salesforce so I am taking an APEX REST in this example to demonstrate integration using JSONP.

Sample Apex Rest sending results in JSONP format:

In this above example, We wrapped the JSON in '()' brackets thus making them in JSONP format.


Callback here is function name in your client side JavaScript that will handle the result. while implementing JSONP ,this is a practice where we can directly send values into any function. it is not mandatory but can be use.Function name was provided in url as query parameter with name of 'callback' or JSONP. Please refer JSONP documentation to know more about it.

Javascript code to hit Apex Rest:

In above javscript, we define that it is a JSONP hit by defining jsonpCallback attribute.


I have used a callback query parameter so that data can be processed directly in processData function . If skipped, data will process in success method of ajax call.

Related post : Integrate salesforce with Jquery/JavaScript

Related Tags:

Salesforce   JavaScript