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

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.

Can anybody please help me?


Finally, I solved the problem. I’m pasting my code here 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)

Source : Link , Question Author : Tushar Kumawat , Answer Author : Tushar Kumawat

Leave a Comment