Integrating Salesforce with Javascript/Jquery (JSONP)

Integrating Salesforce with Javascript/Jquery (JSONP)

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.

Note:

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.

Note:

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

Lakshay Katney Avatar

Lakshay Katney

Saleforce developer by profession but I like to work with various technologies.I blog about Force.com, Hybrid Apps, PhoneGap, AngularJS, BackboneJS, JavaScript in general. I am Angular & NodeJS fan.

Read More
Share this page
Top 15 Posts