Sending data to SOAP API using AngularJS

I've been struggling to send data to a SOAP API but have hit a roadblock. I've attempted various methods but continue to encounter errors when making the API call.

The API URL is -

and it requires data in XML format like

<?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
      <UserRegistration xmlns="http://Service/">
        <Usercreditional>string</Usercreditional>
      </UserRegistration>
    </soap:Body>
  </soap:Envelope>

Methods I've tried -

1> Using $http.post

var soapData = '<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body>'+
'<UserRegistration xmlns="http://Service/">'+
'<Usercreditional>[{ \'DeviceUUID\': \'' + data.DeviceUUID + '\', ' +         
"\"DevicePushID\":\"" + data.DevicePushID + "\"}]" +
'</Usercreditional></UserRegistration></soap:Body></soap:Envelope>';

return $http({ 
         method: 'POST', 
         url: ' http://xyz.asmx?op=UserRegistration', 
         data : soapData, 
         headers : { "Content-Type" : 'application/xml'}
});

This results in the error message "unable to process request. ---> Root element is missing"

2> Using SOAPClient

 var deferred = $q.defer(); 
 var soapParams = new SOAPClientParameters(); 
 var userCredentials = [{"DeviceUUID": data.DeviceUUID, "DevicePushID": data.DevicePushID}]; 
 for (var param in userCredentials )
   { 
       soapParams.add(param, soapParams[param]);
   } 
 var soapCallback = function (e) {
     if (e.constructor.toString().indexOf("function Error()") != -1) {
          deferred.reject(e);
       } else {
          deferred.resolve(e);
       }
   };        
SOAPClient.invoke(' http://xyz.asmx', 'UserRegistration', soapParams, true, soapCallback);
 return deferred.promise;

This is throwing an error stating "Cannot read property 'getElementsByTagName' of null"

Can someone please assist me with this issue? I've exhausted all options without success. Thank you in advance

Answer №1

  1. Utilizing $http.post Method

To send data to SOAP APIs, you can make use of the $http service by following this example:

https://i.sstatic.net/ytqjs.png

var headers = {
                'Content-Type': 'text/xml; charset=utf-8'
            };
 return $http({ 
                method: 'POST', 
                url: 'http://providerservice.fmcnetwork.net/MobileAppService.asmx?op=UserRegistration', 
                data : soapData, 
                headers : headers
            });
  1. Using angular-soap Library

You also have the option to incorporate the angular-soap plugin, which is based on SOAP Client and allows you to utilize the $soap service for the same purpose.

Here's an example:

angular.module('myApp', ['angularSoap'])

.factory("testService", ['$soap',function($soap){
    var base_url = "http://www.cooldomain.com/SoapTest/webservicedemo.asmx";

    return {
        CreateUser: function(firstName, lastName){
            return $soap.post(base_url,"CreateUser", {firstName: firstName, lastName: lastName});
        }
    }
}])

.controller('MainCtrl', function($scope, testService) {

  testService.CreateUser($scope.firstName, $scope.lastName).then(function(response){
    $scope.response = response;
  });

})

Answer №2

Give this a try :)

var soapData = '<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">'+
    '<Body>'+
    '<UserRegistration xmlns="http://FmcMobileApplicationService/">'+
    '<Usercreditional>{ \'DeviceUUID\': \'' + data.DeviceUUID + '\', ' +         
                      "\"DevicePushID\":\"" + data.DevicePushID + "\"}" +
                    '</Usercreditional></UserRegistration></Body></Envelope>';

return $http({ 
            method: 'POST', 
            url: 'http://providerservice.fmcnetwork.net/MobileAppService.asmx'
            data : soapData, 
            headers : { "Content-Type" : 'application/xml'}
        });

Modifications made to your code:

  • Omitted the xml header when sending
  • Changed soap:Envelope to Envelope
  • Eliminated the schema namespaces
  • Updated soap:Body to body
  • Posted to MobileAppService.asmx without the query string
  • Sent an object { "DeviceUUID": "1", "DevicePushID": "2" } instead of an array

I received a response, albeit empty but genuine :) For DeviceUUID and DevicePushID, I utilized 1 and 2 respectively. This could be why I got an empty response.

Response:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <UserRegistrationResponse xmlns="http://FmcMobileApplicationService/">
            <UserRegistrationResult>[]</UserRegistrationResult>
        </UserRegistrationResponse>
    </soap:Body>
</soap:Envelope>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the "return" keyword in Javascript outside of function declarations

Exploring the Impact of Using the Return Keyword in JavaScript Scripts Beyond Functions in Browsers and Node.js Recently, I experimented with utilizing the return keyword in a Node.js script like so: #!/usr/bin/env node return 10; My initial assumption ...

Obtain the specific key's value from a new Map state

In my code, I've defined a variable called checkedItems as a new Map(); When I try to console.log(checkedItem), the output is as follows: Map(3) {"1" => true, "1.5" => true, "2" => false} Is there a way ...

Callback after completion of a for loop in Angular TypeScript

During the execution of my javascript async function, I encountered a situation where my printing code was running before the div creation. I needed to ensure that my print code would run only after the completion of the for loop, but I struggled to find a ...

Steps to enable checkbox functionality in Chakra UI

I need help implementing a checkbox functionality in my project. I am using Chakra UI and trying to achieve a scenario where clicking on the parent checkbox checks all the children checkboxes, but also allows for individual selection. The challenge I am ...

Issue with rendering Backbone subview correctly

Today, I delved into the world of website development using backbone.js. Surprisingly, after a whole morning of trying to crack a puzzling problem, I find myself stuck. Let me focus on the crucial bits of code here. Initially, I have a View named Navigat ...

Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection. Within my controller code: angular.module('mcitygame').directive(&a ...

Updating language settings on-the-fly in a Vue application does not automatically refresh the translated content displayed on the website

My Vue app is quite large, built with Vuetify, and I recently integrated vue-i18n into it. The json translation files are set up correctly, and the $t() calls work fine in my components and other .js files. However, I'm struggling to change the locale ...

Issue with HighCharts Series Data Points Not Being Added

I am currently facing a major challenge in dynamically changing data for highcharts based on date. To provide context for my project, it involves logging system data with timestamps. I have implemented a date and time picker to specify the start and end da ...

css: positioning images with overlap in a responsive layout

Two divs have been created with background images, both displaying the same image but in different colors - one grey and the other green. These images are waveforms. Initially, only the grey image (div1) is visible while the green image (div2) remains hid ...

How can I convert a JSON template to HTML using AngularJS?

As someone who is just starting out with AngularJS, I am facing an issue where the HTML tags in a JSON file are not being encoded when rendered in HTML using AngularJS. Is there a specific method in AngularJS that can help with this? This is what my HTML ...

Using HTML5 and an ASP.NET web method to allow for file uploads

My attempt to upload a file to the server using an HTML5 input control with type="file" is not working as expected. Below is the client-side JavaScript code I am using: var fd = new FormData(); fd.append("fileToUpload", document.getElementById(&ap ...

Develop a personalized event using JavaScript and activate it

I have encountered a problem with a Google ad that expands on click and closes when the close button is hit. However, due to changing conditions, I now need it to expand first and then automatically close after a certain time. Additionally, every time it e ...

"Utilize AJAX to submit the value of the text box input from a jQuery slider when the Submit Button

Whenever I adjust the sliders, the value is shown in an input textbox. However, when I move the slider and check the values echoed from the textboxes on another PHP page, they are always displaying as 0. Even after clicking the submit button, it still echo ...

How to choose a single checkbox in Ionic 2 and retrieve its value

On my single screen, I have about 20 questions and answers retrieved from a database. To display the options, I am using checkboxes but struggling to implement the desired functionality. What I want is to allow only one checkbox selection out of 4 options ...

What are the mechanics behind the functionality of ES6 class instance variables?

I'm encountering an issue with the following code that is not behaving as expected: import React, { Component } from 'react'; let result = null; class MyData extends Component { _getData = () => { fetch(url) .then(response = ...

Navigation issue discovered while trying to implement Ionic's collection-repeat feature

As a newcomer to Ionic and Angular.js, I recently downloaded an example of an ionic collection repeat and navigation from http://codepen.io/ionic/pen/mypxez. Initially, the example worked perfectly with just single index.html and index.js files. However, I ...

There seems to be an issue with d3js bar charts as they are not displaying on the screen and there

Recently, I started delving into the world of D3js and decided to try my hand at creating some bar charts. However, despite my efforts, the bar charts failed to display on the screen. <!DOCTYPE HTML> <html> <head> <title> My D3 Pra ...

Maximizing jQuery DataTables performance with single column filtering options and a vast amount of data rows

My current project involves a table with unique column select drop-downs provided by an amazing jQuery plug-in. The performance is excellent with about 1000 rows. However, the client just informed me that the data could increase to 40000 rows within a mont ...

Button within the Magnific Popup (do not use to close)

I am currently developing a website with a gallery page that utilizes the Magnific Popup plugin. My client has provided lengthy 'captions' for each image, almost like short stories. To display these captions effectively, I have utilized the titl ...

Tips for choosing elements that are not next to each other in a JavaScript array

If I have an array and want to select non-consecutive elements, such as the second and fifth elements, is there a simple method to do this? For example: a = ["a","b","c","d","e"] a.select_elements([1,4]) // should yield ["b","e"] EDIT: After some reflec ...