1

In salesforce, on hitting a button I need to call a web service url through an ajax call.

Please check my code below :

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
          var response = xmlhttp.responseText; 
                      }
                    } 
     var requrl ='my webservice url';
                       alert(requrl);
                       xmlhttp.open("POST",requrl);
                       xmlhttp.send();

When I hit this 'requrl' manually on browser, it works fine. Can anyone tell me what I am doing wrong above or provide me a sample code against this?

Neha
  • 143
  • 4
  • 19

2 Answers2

0

From You Might Not Need jQuery:

var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
romellem
  • 5,792
  • 1
  • 32
  • 64
  • I tried this, it gives an error on console - " Blocked loading mixed active content " – Neha Apr 27 '16 at 05:55
  • That happens when you're on an HTTPS page and try to hit a plain HTTP via your ajax request. The URL you're trying to post to is on the same domain, correct? – romellem Apr 27 '16 at 12:35
  • You are right. My salesforce domain is https and of my webservice url (as mentioned "requrl" ) is http . So, what shall I do now? – Neha Apr 27 '16 at 12:43
  • I also tried below code j$.ajax({ url : requrl, type: 'GET', headers: { "Content-Type":"text/xml; charset=UTF-8" }, success: function(data, textStatus, jqXHR){ alert('data is : '+$(data)); }, error:function(jqXHR, textStatus, errorThrown){ alert('textStatus->'+textStatus); } }); – Neha Apr 27 '16 at 12:44
  • Well, you're always going to get that mixed content because of HTTPS vs HTTP, there isn't any way around that. But for cross domain requests, you probably have to set CORS headers in your ajax call. Since you said you're using jQuery, [this post](http://stackoverflow.com/questions/298745/how-do-i-send-a-cross-domain-post-request-via-javascript) may be useful. I'd do searches on "Cross Domain AJAX requests" to find more info if you need it. – romellem Apr 27 '16 at 12:48
  • Thanks :) ,I will also search on above . One more thing, I tried by adding " crossDomain: true, " in my ajax call according to the post you shared above, but didn't help me either. – Neha Apr 27 '16 at 12:56
0

Have you set the requrl as a remote site (https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_remotesitesetting.htm) ?

cafecoder
  • 16
  • 2