Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call SOAP WS from Javascript/jQuery

I would like to call a SOAP WebService directly from Javascript. I have been looking all around but still is unable to have something working. I assumed that i must build the SOAP enveloppe (see below). I also use jQuery.

Firstly, I would be sure that I can call a SOAP Webservice located somewhere else ? that is there is no limitation like cross domain limitation.

Also I am not sure what is the right URL i need to use, SOAP Service is exposed using Ladon, for debugging purpose I have checked that the WS works well with soapUI, and here are the URLs that i can find :

  • WSDL URL : http://192.168.1.5/ws/MyWS/soap/description // from my understanding it can not be this one
  • service endpoints : http://192.168.1.5/ws/MyWS/soap
  • SOAPAction: http://192.168.1.5/ws/MyWS/soap/myOperation

i think that i should use endpoint or SOAPAction but it did not work. I may miss something here or the later Javascript is so faulty that i can not be sure.

Now here is my actual JS doing the call (there are some questions inside comments):

<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<head>

<script type="text/javascript" src="ressources/jquery-1.7.1.min.js"></script>

<script type="text/javascript">

// inspired by http://openlandscape.net/2009/09/25/call-soap-xm-web-services-with-jquery-ajax/

var soapServiceURL = 'http://192.168.1.5/ws/MyWS/soap/myOperation; // not sure what to put here from a LADON point of view

function callSOAPWS(myParameter)
{
  var soapMessage =
  '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:LDetector"> \
     <soapenv:Header/> \
     <soapenv:Body> \
        <urn:myOperation soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> \
           <myParameter xsi:type="xsd:string">' + myParameter + '</myParameter > \
        </urn:myOperation > \
     </soapenv:Body> \
  </soapenv:Envelope>';

  alert("Check SOAP: [" + soapMessage + "]");

  jQuery.ajax({
          url: soapServiceURL,
          type: "POST",
          dataType: "xml",
          data: soapMessage,
          contentType: "text/xml; charset=\"utf-8\"",

          //processData: false,   // what is it for? may be should be true when using 'complete:' ?
          //timeout: 5000,

          // below I first try to have only 'complete:' then I tried to have 'success:' + 'error:', then the 3. Nothing seems to be ok. I do not find which one i should use.
          complete: myCallback,

          success: function( response ){
              document.getElementById('debug').innerHTML = document.getElementById('debug').innerHTML + '\n' + 'success!' + '\n';
              alert("success!!!");
          },

          error: function(XMLHttpRequest,textStatus, errorThrown){
              document.getElementById('debug').innerHTML = document.getElementById('debug').innerHTML + '\n' + 'error : ' + textStatus + '\n';
              alert("error : " + textStatus);
          }

  });

  alert('if we reach this line, is it a fail?!');
  return false;
}

function myCallback(xmlHttpRequest, status)
{
  jQuery(xmlHttpRequest.responseXML)
      .find('detected')
      .each(function()
   {
     var result = jQuery(this).find('result').text();
     document.getElementById('debug').innerHTML = document.getElementById('debug').innerHTML + '\n' + result + '\n';
     alert('ok : [' + result + ']');
   });
}

// https://stackoverflow.com/questions/11916780/changing-getjson-to-jsonp?rq=1

jQuery(document).ready(function() {
    callSOAPWS('this is a test');
});

</script>
</head>
<body>

<div id="debug" style="background-color:#EEEEEE; height:250px; width:600px; overflow:auto;">&nbsp;</div>

</body>
</html>

best regards

EDIT: while continuing to try and search an answer, i have readed that => Simplest SOAP example where Prestaul say "This cannot be done with straight JavaScript unless the web service is on the same domain as your page." so, maybe i'm trying to do something impossible? is it the reason why it can not work?

like image 465
user1340802 Avatar asked Oct 09 '12 09:10

user1340802


3 Answers

You cannot send cross domain AJAX requests because of the same origin policy restriction that's built into the browsers. In order to make this work your HTML page containing the jQuery code must be hosted on the same domain as the Web Service (http://192.168.1.5/ws/MyWS/).

There are workarounds that involve using JSONP on the server, but since your web service is SOAP this cannot work.

The only reliable way to make this work if you cannot move your javascript on the same domain as the web service is to build a server side script that will be hosted on the same domain as the javascript code and that will act as a bridge between the 2 domains. So you would send an AJAX request to your server side script which in turn will invoke the remote web service and return the result.

like image 84
Darin Dimitrov Avatar answered Nov 15 '22 01:11

Darin Dimitrov


How about this? https://github.com/doedje/jquery.soap

Seems easy enough. Maybe it will help you.

Example:

$.soap({
url: 'http://my.server.com/soapservices/',
method: 'helloWorld',

data: {
    name: 'Remy Blom',
    msg: 'Hi!'
},

success: function (soapResponse) {
    // do stuff with soapResponse
    // if you want to have the response as JSON use soapResponse.toJSON();
    // or soapResponse.toString() to get XML string
    // or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
    // show error
}
});

will result in

<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <helloWorld>
        <name>Remy Blom</name>
        <msg>Hi!</msg>
    </helloWorld>
  </soap:Body>
</soap:Envelope>
like image 23
geekasso Avatar answered Nov 15 '22 02:11

geekasso


below code is working fine. may be it may help you.

    var SoaMessage = '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" >'
                + '<soapenv:Header/>'
                  + '<soapenv:Body>'
                    + '<myoperation soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns="http://MyService/"> '
                     + ' <AgencyId xsi:type="xsd:string">ADBC</AgencyId >'
                  + '</myoperation >'
                 + '</soapenv:Body>'
             + '</soapenv:Envelope>';
    var url = "http://XXXXXXX/XXX/XXXXX?wsdl";
    $.support.cors = true;
    $.ajax({
        type: "POST",
        url: url,
        jsonpCallback: "MyCallbackDED",
        dataType: "xml",
        processData: false,
        contentType: "text/xml; charset=\"utf-8\"",
        success: function (msg) {
            alert("suc: " + msg.tradeLicenseData.master[0].arabicAddress + ": " + msg.tradeLicenseData.master[0].arabicAddress);

        },
        error: function (msg) {
            alert("Failed: " + msg.status + ": " + msg.statusText);
        }

    });
like image 1
AbdulAzizFarooqi Avatar answered Nov 15 '22 01:11

AbdulAzizFarooqi