Skip to content

Instantly share code, notes, and snippets.

@henriquez
Created July 19, 2012 21:00
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save henriquez/3146782 to your computer and use it in GitHub Desktop.
Save henriquez/3146782 to your computer and use it in GitHub Desktop.
Example Javascript that uses ajax proxy to make request to Chatter API
<apex:page controller="CustomerCommunityController" id="customercommunitycontroller" sidebar="false" showHeader="false" standardStylesheets="false" >
<head>
<title>Acme Customer Support</title>
<meta charset="utf-8" />
<apex:includeScript value="{!$Resource.jquery}"/>
</head>
<script type="text/javascript">
/* Same Origin Policy limits javascript running in VisualForce pages from making requests to
APIs, even salesforce apis, because they are hosted on salesforce.com while visualforce
pages are served from force.com. To work around this, configure an ajax proxy in your organization.
Ajax proxies are configured in setup under Security Controls | Remote Site Settings. Put in a URL
into the proxy like https://na1.salesforce.com (or whatever the domain of the api is)
Once configured, just plain javascript can use the proxy url, which is available at /services/proxy
The Salesforce Ajax Toolkit is not required, and generally you don't want to use that anyway, since
its not supported on Safari or Chrome.
Here's a basic example of how to make a request to the Chatter REST API from a Visualforce page.
This also works for portal(community) users and portal pages.
*/
(function() {
var $;
$ = jQuery;
$(function() {
var credential = ' OAuth ' + '{!GETSESSIONID()}'; // native VF function
var apiUrl = "https://na1.salesforce.com/services/data/v26.0/chatter/users/me";
$.ajax({
type: "GET",
// for community pages, use whole community url including path, e.g.
// https://logan.blitz01.t.force.com/customers/services/proxy.
url: "https://c.na1.visual.force.com/services/proxy",
contentType: 'application/json',
cache: false,
success : function(response) {
alert("result" + response);
},
error : function(response) {
alert("Failed" + response);
},
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader('SalesforceProxy-Endpoint', apiUrl);
xhr.setRequestHeader("Authorization", credential);
xhr.setRequestHeader('X-User-Agent', 'MyClient');
}
});
});
}).call(this);
</script>
This is your new Page
</apex:page>
@richardvanhook
Copy link

I have similar example avail here: https://gist.github.com/4677449

@bleyle
Copy link

bleyle commented Jun 5, 2013

As of Summer '13, you can also use Chatter in Apex to access Chatter REST API resources using Apex classes.

http://www.salesforce.com/us/developer/docs/apexcode/Content/connectAPI_overview.htm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment