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
https://ap1.salesforce.com/services/apexrest/CustomSettings. Origin
https://c.ap1.visual.force.com 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.

Can anybody please help me?

Answer

Finally, I solved the problem. I’m pasting my code here for reference

    var result = sforce.connection.login("myname@mymail.com", "mypassword+mysecurityToken");
    sforce.connection.init('{!sessionId}', 'REST web service url'); // here pass current session id of the org from which you are making request.

    sforce.connection.remoteFunction({
           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) {
                  console.log(response);
              },
           onFailure : function(response) {
                  alert("Failed" + response)
              }
       });

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

Leave a Comment