Skip to Content

This is a useful blog for beginners in ui5. This shows an example to consume the webservice in ui5 application. There are different ways in which this can be achieved. I have shown 2 methods in this blog. In both the methods, the input xml to the webservice is posted and the response is taken.

  • Parsing the xml response received from the webservice

var textArea = new sap.ui.commons.TextArea({
                     id : "textArea1"
});
var request = "<Your input xml to the webservice>”;
                    var response = "";
          $.ajax({
                 url : "Your webservice wsdl url",
                 type : "POST",
                 data : request,
                 dataType : "text",
                 contentType : "text/xml; charset=\"utf-8\"",
                 success : function(data, textStatus, jqXHR) {
                        response = data;
                 },
                 error: function(xhr, status)
                 {
                        console.log("ERROR");     
                 },
                 complete : function(xhr,status) {
                        uicontrols();
                 }
          });
                           function uicontrols(){
                     parser=new DOMParser();
                     xmlDoc=parser.parseFromString(response,"text/xml");
                                         var returnVal = xmlDoc.getElementsByTagName("The tag from response xml which you want")              [0].childNodes[0].nodeValue;
                     textArea.setValue(returnVal); //set the value to textArea
          }
  • Using XML model


var request = "<Your input xml to the webservice>”;
                            var response = "";
              $.ajax({
                     url : "Your webservice wsdl url",
                     type : "POST",
                     data : request,
                     dataType : "text",
                     contentType : "text/xml; charset=\"utf-8\"",
                     success : function(data, textStatus, jqXHR) {
                           response = data;
                     },
                     error: function(xhr, status)
                     {
                           console.log("ERROR");     
                     },
                     complete : function(xhr,status) {
                           uicontrols();
                     }
              });
var oModel = new sap.ui.model.xml.XMLModel(); 
                           function uicontrols(){
                     oModel.setXML(response);
}
var oTable = new sap.ui.table.Table({
                     id: "table1"
});
             oTable.addColumn( 
                                          new sap.ui.table.Column({       
                                  label: new sap.ui.commons.Label({text: "Label1"}),       
template: new sap.ui.commons.TextField().bindProperty("value", "Tag1/text()") 
})
              );
              oTable.addColumn( 
                                          new sap.ui.table.Column({       
                                  label: new sap.ui.commons.Label({text: "Label2"}),       
template: new sap.ui.commons.TextField().bindProperty("value", "Tag2/text()") 
})
);
             oTable.setModel(oModel);  
             oTable.bindRows({path: "/the main XML tag under which Tag1 and Tag2 are present/"});


Thank you,

Navya

To report this post you need to login first.

12 Comments

You must be Logged on to comment or reply to a post.

    1. Swati Joshi

      Hi Navya,

      Nice post you have shared, I followed same and trying to get response of my webservice in UI5 view but it showing me error

      ParseError.PNG

      I have created JS view in my ui5 application and there i have writte below code

      function(oController) {

      var request = ‘<soapenv:Envelope xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:urn=”urn:ValidateuserwebserviceVi”>’

      +'<soapenv:Header/><soapenv:Body>’

      +'<urn:Validateuser><urn:Uname>X1801</urn:Uname>’

      +'<urn:Password>asdf@123</urn:Password>’

      +'</urn:Validateuser>’

      +'</soapenv:Body></soapenv:Envelope>’;

      var response = “”;

      $.ajax({

      url : ‘https://10.189.7.13:50101/Validateuserwebservice/ConfigValidate?wsdl‘,

      type : ‘POST’,

      dataType  : ‘xml’

      data : request,

      contentType : ‘text/xml; charset=\”utf-8\”‘,

      success : function(data, textStatus, jqXHR) {

          

      response = data;

      console.log(“data”+data);

      }

      error : function(){

      console:log(‘ERROR’);

      }

      complete : function(xhr,status) { 

      uicontrols();

      }

      });

      var oModel = new sap.ui.model.xml.XMLModel();             

      function uicontrols(){ 

      var oModel = new sap.ui.model.xml.XMLModel();

      var oModel =  sap.ui.model.xml.XMLModel();

      oModel.setXML(response);

      alert(“GETXML>>>>”+oModel.getXML());

      var oPage1=new sap.m.Page({

      title : “Test Service”

      });

      return oPage1;

      }}

      );

      Here when i check alert(“GETXML>>>>” value it is showing error in parasing .I am using my own webservice which have request

      <soapenv:Envelope xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:urn=”urn:ValidateuserwebserviceVi”>

         <soapenv:Header/>

         <soapenv:Body>

            <urn:Validateuser>

               <urn:Uname>X1801</urn:Uname>

               <urn:Password>asdf@123</urn:Password>

            </urn:Validateuser>

         </soapenv:Body>

      </soapenv:Envelope>

      and on running it on soap ui it showing response

      <SOAP-ENV:Envelope xmlns:xs=”http://www.w3.org/2001/XMLSchema” xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance“>

         <SOAP-ENV:Body xmlns:rpl=”urn:ValidateuserwebserviceVi”>

            <rpl:ValidateuserResponse xmlns:rn0=”java:sap/standard” xmlns:rn1=”http://schemas.xmlsoap.org/soap/encoding/“>

               <rpl:Response>User verified.</rpl:Response>

            </rpl:ValidateuserResponse>

         </SOAP-ENV:Body>

      </SOAP-ENV:Envelope>

      Urgent help needed as without this response i can not possible to proceed with.Please help me step by step process if i am missing some thing or if some demo project avaialble please share that.

      (0) 
    1. Vijaykumar Ratnakar

      Hi Vinayak,

      This is cross domain issue, which is cuased if the requesting website is served from different domain(localhost) and requested resources are served out of different domain (gateway url).quick fix for development could be, opening the chrome with disabled web security.

      Execute following command in command prompt ( Make sure that all the instances of chrome are closed before executing following commands)

      cd C:\Program Files\Google\Chrome\Application (Change this path accordingly)

      chrome –disable-web-security

      Now in opened browser execute the localhost url, app should work fine.

      One more way is to use proxy servelets :

      The information for the same can be found here

      Use a SimpleProxyServlet for Testing to Avoid Cross-domain Requests – UI Development Toolkit for HTML5 (SAPUI5) – SAP Li…

      Regards,

      Vijay.

      (0) 
  1. A K

    Hi,

    Nice try 🙂 ..But I have few queries.

    1. Why you preferred ajax call?

    Already SAP have odata methods to call GW/webservices.

    OData Model have autoupdate properties as well as more features are appended into oDATA models.

    It could be very useful to you if you used odata model instead of ajax call.

    Thanks,

    Karthik A

    (0) 
    1. Vijaykumar Ratnakar

      Hi Karthik,

      I Agree with the argument sapui5 odata model is more matured, it not only helps in CRUD operations, also provides nice binding – templating feature which intern takes care of filtering pagination with ease – by just switching on or off few properties of the control.

      How ever above approach could be useful to consume non oData services like SOAP services or simple REST services.

      Regards,

      Vijay.

      (0) 
    2. Hieu Nguyen Minh

      Hello Karthik,

      Aggree with you, but sometime backend can not provide Odata service for some reason (in my case, they return XS JS service). Hence we need to use ajax call.

      I’m finding how to use ajax call & get over cross-domain policy. If you have ideas on this, please help me out.

      THanks a lot!

      (0) 
      1. A K

        HI Hieu- Thank you for your comments. I really appreciate your effort to bring up this conversation now.

        I badly need your help on XMLHTTPREQUEST for SAP_ML_API. Can you please help me on it???

        While executing below API call from browser I am getting the attached error, if you have idea please share it with us. 🙂

        Code:

        var data = JSON.stringify({
        				"sourceLanguage": "de",
        				"targetLanguages": [
        					"en"
        				],
        				"units": [{
        					"value": "Der Bestellvorgang bricht beim Speichern der Lieferadresse ab."
        				}]
        			});
        
        			var xhr = new XMLHttpRequest();
        			//xhr.withCredentials = true;
        
        			xhr.addEventListener("readystatechange", function() {
        				if (this.readyState === this.DONE) {
        					console.log(this.responseText);
        				}
        			});
        
        			//setting request method
        			xhr.open("POST", "https://sandbox.api.sap.com/ml/translation/translate");
        			//adding request headers
        			xhr.setRequestHeader("Content-Type", "application/json");
        			xhr.setRequestHeader("Accept", "application/json;charset=UTF-8");
        			xhr.setRequestHeader("APIKey", "<GIVEN CODE>");
        			xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
        			xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,  PUT,  POST,  DELETE");
        			xhr.setRequestHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
        			xhr.setRequestHeader("Access-Control-Max-Age", "3600");
        			//sending request
        			xhr.send(data);

         

        Regards,

        Karthik A

        (0) 
        1. Ashwini M

          Hello Karthik,

          I’m also trying to consume a machine learning API using a UI5 application.

          Were you able to succeed in your effort, if so please provide your insights.

          Thanks,

          Ashwini

           

          (0) 
  2. Rubens Walter Blättler

    Hello, Navya!
    I developed a small application based in your first example using the SAP WEB IDE.
    Below follows the source code of my XML view (View1):

    <mvc:View xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="TestWebService.controller.View1" displayBlock="true">
    <App>
    <pages>
    <Page title="Call WebService from SAPUI5 (Correios Interface)">
    <content>
    <Button text="Call WebService" width="300px" id="__button0" press="callWebService"/>
    <TextArea id="textArea1" rows="10" cols="150" placeholder="Response message" editable="false"/>
    </content>
    </Page>
    </pages>
    </App>
    </mvc:View>

    Below follows the source code of my view controller:

    var requestMessage;
    var responseMessage;
    var endPointWSDL;
    
    sap.ui.define(["sap/ui/core/mvc/Controller"], function(Controller) {
    	"use strict";
    return Controller.extend("TestWebService.controller.View1", {
    		
    onInit: function() {
    requestMessage = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">';
    requestMessage = requestMessage.concat("<soapenv:Header/>");
    requestMessage = requestMessage.concat("<soapenv:Body>");
    requestMessage = requestMessage.concat(" <tem:CalcPrecoPrazo>");
    requestMessage = requestMessage.concat("<tem:nCdEmpresa>49436</tem:nCdEmpresa>");
    requestMessage = requestMessage.concat("<tem:sDsSenha></tem:sDsSenha>");
    requestMessage = requestMessage.concat("<tem:nCdServico>40010</tem:nCdServico>");
    requestMessage = requestMessage.concat("<tem:sCepOrigem>05422030</tem:sCepOrigem>");
    requestMessage = requestMessage.concat("<tem:sCepDestino>06026090</tem:sCepDestino>");
    requestMessage = requestMessage.concat("<tem:nVlPeso>1</tem:nVlPeso>");
    requestMessage = requestMessage.concat("<tem:nCdFormato>3</tem:nCdFormato>");
    requestMessage = requestMessage.concat("<tem:nVlComprimento>20.00</tem:nVlComprimento>");
    requestMessage = requestMessage.concat("<tem:nVlAltura>0</tem:nVlAltura>");
    requestMessage = requestMessage.concat("<tem:nVlLargura>12.00</tem:nVlLargura>");
    requestMessage = requestMessage.concat("<tem:nVlDiametro>0</tem:nVlDiametro>");
    requestMessage = requestMessage.concat("<tem:sCdMaoPropria>N</tem:sCdMaoPropria>");
    requestMessage = requestMessage.concat("<tem:nVlValorDeclarado>0</tem:nVlValorDeclarado>");
    requestMessage = requestMessage.concat("<tem:sCdAvisoRecebimento>N</tem:sCdAvisoRecebimento>");
    requestMessage = requestMessage.concat("</tem:CalcPrecoPrazo>");
    requestMessage = requestMessage.concat("</soapenv:Body>");
    requestMessage = requestMessage.concat("</soapenv:Envelope>");
    responseMessage = "";
    endPointWSDL = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx?WSDL";
    },
    		
    //on press button:
    callWebService: function() {
    			
    var textArea = new sap.ui.commons.TextArea({ id : "textArea1" });
    			
    function uicontrols(){
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(responseMessage,"text/xml");
    var returnVal = xmlDoc.getElementsByTagName("Servicos")[0].childNodes[0].nodeValue;
    textArea.setValue(returnVal); //set the value to textArea
    }
              
    $.ajax({
    url : endPointWSDL,
    type : "POST",
    data : requestMessage,
    dataType : "text",
    contentType : "text/xml; charset=\"utf-8\"",
    success : function(data, textStatus, jqXHR) {
    responseMessage = data;
    },
    error: function(xhr, status)
    {
    sap.ui.commons.MessageBox.alert("Error to consume WebService");
    },
    complete : function(xhr,status) {
    uicontrols();
    }
    });
              
    }
    		
    });
    });

    Could you tell me what I’m doing wrong, please?
    Thank you very much!
    Rubens

    (0) 
  3. Raghavendra H K

    Hi Navya,

    For consuming oData services I can create destination and I could able to get the data in component.js,

    But in my workflow I am using XSOData ….In my  scenario I need to post the data in component.js for Hana database ….Is it possible to call hana services in component.js?

    Thanks & Regards,

    Raghavendra H K

    (0) 

Leave a Reply