function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ScottWellsScottWells 

How can I invoke Apex RESTful services from VisualForce pages?

I'm in the process of integrating jqGrid into a VisualForce page, ideally using a JSON data source provided by Apex RESTful services.  At this point it keeps telling me that the session is invalid, so I'm trying to figure out what to do.

 

My Apex RESTful service class looks like:

 

@RestResource(urlMapping='/jqGrid/*')
global with sharing class JqGridController
{
    @HttpGet
    global static JqGridResponse doGet()
    {
        ...
    }
}

 

and the referencing VisualForce page contains the following:

 

jQuery('#{!gridId}').jqGrid(
{
    datatype: 'json',
    url: "{!URLFOR('/services/apexrest/jqGrid')}",
    loadBeforeSend: function(jqXHR)
    {
        jqXHR.setRequestHeader("Authorization", "Bearer {!URLENCODE($Api.Session_Id)}");
    },
    ...
});
...

Does anyone know why this isn't working and, more importantly, what I need to do to get it working?

 

Thanks!

 

ScottWellsScottWells

Never mind.  I figured it out!  I was using the API session ID but I needed to be using the authenticated user's current session ID (UserInfo.getSessionId()).  It's also important that this header value *not* be URL-encoded because the AJAX request already does that and you'll end up with a decoded session ID that's invalid.

 

Hope this helps someone else in the future!!!

ScottWellsScottWells

Well, I may have spoken too soon.  While that did get me past that issue, it unveiled a larger issue that seems to have to do with a potential CSS vulnerability.  Basically the VisualForce page is being served as a visual.force.com domain URL while the Apex RESTful service is being exposed in the salesforce.com domain.  When jquery makes its request, it does so initially using the HTTP OPTIONS method because its cross-domain, and as far as I can tell the Salesforce.com servers don't support this method.

 

Anyone have any thoughts?  I'm hoping that this is possible because it seems like the logical convergence of VisualForce and APEX RESTful services!

 

Thanks again!

RohanGoreRohanGore
Hi Scott,

Ealier Apex Rest service is neither exposed on a visualforce domain/server nor does it used to support CORS whitelisting.CORS whitelisting is possible now for Apex Rest endpoints as well.
Please refere this dcoument: https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/extend_code_cors.htm.