I'm new to rest services in Salesforce. I've defined the following rest service in Apex:

global with sharing class MediaPlanDetailService {

    global static String doGet() {

        RestResponse response = RestContext.response;    
        response.addHeader('Access-Control-Allow-Origin', '*');
        response.addHeader('content-Type', 'application/json');

        String URL = 'http://services.somecompany.com/services/loadByMediaPlanId';

        String payloadStr = '';

        String rows = RestContext.request.params.get('rows');  System.debug('rows = ' + rows);
        String page = RestContext.request.params.get('page');  System.debug('page = ' + page);
        String sidx = RestContext.request.params.get('sidx');  System.debug('sidx = ' + sidx);
        String sord = RestContext.request.params.get('sord');  System.debug('sord = ' + sord);
        String mediaPlanId = RestContext.request.params.get('mediaPlanId');
        String pageSize = RestContext.request.params.get('pageSize');

        String finalUrl = URL + 
                '?rows=' + rows +
                '&page=' + page + 
                '&sidx=' + sidx + 
                '&sord=' + sord + 
                '&mediaPlanId=' + mediaPlanId +
                '&pageSize=' + pageSize +

        Http objhttp = new Http();
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();


        req.setHeader('Content-type','application/json; charset=UTF-8');
        req.setHeader('Accept-Language', 'en-US');

        try {
            res = objhttp.send(req);

            if(res.getStatus().equalsIgnoreCase('OK') && res.getStatusCode() == 200) {
                // Logic to parse the response
                String body = res.getBody();
                system.debug('-------- HttpResponse received: ' + body);

                final String PAYLOAD_ELEMENT = '\"payload\":';
                final String EXCEPTION_ELEMENT = '\"exception\":';

                integer payloadPos = body.indexOf(PAYLOAD_ELEMENT); System.debug('payloadPos = ' + payloadPos);
                integer exceptionPos = body.indexOf(EXCEPTION_ELEMENT); System.debug('exceptionPos = ' + exceptionPos);

                payloadStr = body.substring(payloadPos + PAYLOAD_ELEMENT.length(), exceptionPos - 1);


        catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);

        return payloadStr;


I'm calling this service using a jQuery plugin call jqGrid. Here's a snippet of the code:

$(document).ready(function () {

    var mpId = $.urlParam('mediaPlanId');

    url: '/services/apexrest/mediaPlanDetail',  // this fails with 302 Found
    //url: 'https://somecompany--cpq.cs7.my.salesforce.com/services/apexrest/mediaPlanDetail',  // this fails with 401 not authorized
    postData: {
        mediaPlanId: mpId,
        pageSize: 10
    loadBeforeSend: function(jqXHR) {
        //jqXHR.setRequestHeader("Authorization", 'OAuth ' + __sfdcSessionId);
        jqXHR.setRequestHeader("Authorization", 'Bearer {!$Api.Session_ID}');
        //jqXHR.setRequestHeader("Authorization", 'OAuth {!$Api.Session_ID}');

The VF page where I'm calling the service has this location:


When I call the service using


the service returns a 302 with an alternative Location in the header:


When I use the redirected location as the URL, I get a 401 Unauthorized response with Cross-Origin Request Blocked messages in my browser.

In either case, my Apex rest service is never called. I see nothing in the Debug Logs indicating that my browser is actually calling it.

This looks like a classic cross domain scripting issue between the Salesforce VP page domain and the domain used for Apex rest services. I spent a lot of time yesterday reading various posts on both calling SF rest services and cross domain issues, but wasn't able to find a solution. Can anyone help me with this?

3 Answers 3


A quick google search return pretty helpful results:


function CallRestAPI()
var weblink = "http://URL";

url : weblink,
type : 'GET',
dataType: 'json',
beforeSend: function (request)
request.setRequestHeader("HeaderName", "HeaderValue");
crossDomain: true,
success : function(result)
    //process the result
error : function(jqXHR, textStatus, errorThrown) {
alert('Error: '+jqXHR.status);
alert('ErrorThrown: '+errorThrown)



I would think the JS removing would be a MUCH better case, call the remote method and have that method call the web service directly.

  • I tried adding j$.ajaxSetup({crossDomain:true}); and j$.ajax({crossDomain:true}); to my page. I still get the same errors. Commented Jul 24, 2015 at 14:37

There is a known behavior of Apex REST services that calls from the VF domain are not considered safe in the same origin policy.

To work around this the forcetk library from the force.com Javascript REST toolkit will allow you to make such calls via a proxy.

Although, I'm not sure that is necessary in this instance. You could, instead, use the @RemoteAction Apex annotation instead. Unless you're finding the request size is too big or something.

  • I'm not having any luck getting forcetk to work. I'll post a new question on that. Appreciate your help! Commented Jul 24, 2015 at 16:31

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    // https://salesforce.stackexchange.com/questions/84766/cannot-call-apex-rest-service-from-jquery-on-visualforce-page
    $(document).ready(function () {
        var sessionId = '00AAA000000BBBB!YYYY_ZZZZ_.VVV_WWW.PPP_QQQ_RRR.SSS';
            method: "POST",
            url: 'https://csMM.salesforce.com/services/apexrest/NNN/updateLLL',
            data: `{
                "request": [
                        "action": "FFF",
                        "startDate": "2018-01-01T00:00:00.000Z",
                        "moreParameters": "..."
            processData: false,
            // "For cross-domain requests, setting the content type to anything
            // other than application/x-www-form-urlencoded, multipart/form-data, or
            // text/plain will trigger the browser to send a preflight OPTIONS request
            // to the server"
            // On the other hand, sending Content-Type: text/plain... meets HTTP 415 Unsupported Media Type
            // The best match for JSON worked with the OPTIONS preflight
            // request (but required sending a text in data with processData set
            // to false).
            contentType: "application/json; charset=UTF-8",

            // The response comes with "Content-Type: application/octetstream" as a JSON text.
            dataType: "json",
            jsonp: false,

            // The "withCredentials" flag causes Firefox refuse sending the
            // POST after OPTIONS because Salesforce declares "do not send cookies
            // in your data requests" with the following response header,
            //  Access-Control-Allow-Credentials: false.
            // On the other hand Salesforce's OPTION response also has
            //  Access-Control-Allow-Headers: X-SFDC-Request-Id,authorization,content-type
            // which seems sufficient for Firefox to proceed with POST after commenting out
            // withCredentials.
            // xhrFields: {
            //     withCredentials: true
            // },
            headers: {
                "Authorization": "Bearer " + sessionId
        }).done(function( data, textStatus, jqXHR ) {
            // To let the browser access the returned data, add the
            // URL of the site hosting this HTML page in
            //   https://csMM.salesforce.com
            // under Setup / Quick Find / CORS / New.
        }).fail(function( jqXHR, textStatus, errorThrown ) {
        Hello, world.
        <span id="output"></span>
        <span id="error"></span>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .