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

How to call Apex REST API from Javascript?



I have two different developer orgs. One contains apex REST web service, and I want to call that REST service from my second org. I have tried to call that REST service using normal ajax post request and forcetk.js, But I got following error


XMLHttpRequest cannot load Origin is not allowed by Access-Control-Allow-Origin.


I searched about this problem then I got to know that Salesforce never allows CORS (Cross-Origin-Resource-Sharing).


Initially I was using apex to call that REST web service, that time I was able to post data from apex. But as we have callout limitation in salesforce, I want to use javascript.


Please help me.




Best Answer chosen by Admin (Salesforce Developers) 
Tushar RKTushar RK

Here I'm pasting my code for reference



var result = sforce.connection.login("", "mypassword+mysecurityToken");
sforce.connection.init('{!sessionId}', 'REST web service url');

// here pass current session id of the org from which you are making request.


          url : REST web service url,
          requestHeaders: {"Authorization":"Bearer "+result.sessionId, "Content-Type":"application/json"},

          // here pass the session id of the org in which you have your REST service
          requestData: data to post in JSON format,
          method: "POST",
          onSuccess : function(response) {
          onFailure : function(response) {
                    alert("Failed" + response)