Here, here is my JavaScript code within a VisualForce page. The query is guaranteed to return only one result. but I am getting "Invalid Session ID" exception. please help.

    function queryPricingModel()
        sforce.connection.sessionId = '{!$Api.Session_ID}';

            var myQuery = sforce.connection.query("SELECT BP__c FROM PC_BP_Matrix__c WHERE StartVolume__c <= annualVolume AND EndVolume__c > annualVolume");
            pcBP = myQuery;
        catch (error)

3 Answers 3


Last time I used AJAX toolkit, it was necessary to put the Session ID in a crazy magic global variable before loading the library:

<!-- this guy first -->
<script type="text/javascript">__sfdcSessionId = '{!$Api.Session_Id}';</script>

<!-- this guy second -->
<script src="/soap/ajax/29.0/connection.js" type="text/javascript"></script>
  • Can you explain? I have my javascript in a separate file in the static resource. I know I can access the global variable from the js file. But I'm not sure how do I use the variable. Commented Jan 16, 2014 at 14:43
  • 1
    Worked great! / you're awesome - Thanks!
    – sean2078
    Commented Jan 1, 2016 at 22:51

Try this to get the session Id:

 var sfdcSessionId = '{!GETSESSIONID()}';

It looks like you are trying to set the SessionId, and not all Session Ids are the same: Different Session Ids in Different contexts

Also, Salesforce provides a good example for the AJAX Toolkit.


Can you alert() that session id? Is it blank by any chance? Is the user authenticated (it's not something like a Site where any external user can get)?

You've used - but for example Using Salesforce Partner API from community portal indicates there are problems with API access in communities.

Can you try to rework your Visualforce page to either use pure Apex & VF or maybe some JS remoting?

You must log in to answer this question.

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