Parsing XML soap responses in JavaScript

I'm utilizing Javascript to interact with a SOAP webservice. Through firebug, I can confirm that the request has been successful and I am able to view the XML SOAP response.

How can I showcase this response on the webpage? Or even better - is there a way to display a specific node within the XML SOAP response? I had considered using XPath, but it doesn't seem to be functioning as expected.

Below is the code snippet:

<html>
<head>
    <title>SOAP Client Test</title>
    <script type="text/javascript">
        function soap() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open('POST', 'https://mysoapurl.com', true);

            // Construct SOAP request
            var sr =
                '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">' +
                    '<s:Header> ' +
                        '<USERNAME xmlns="http://www.tempuri.org">MyUsername</USERNAME>' +
                        '<PASSWORD xmlns="http://www.tempuri.org">MyPassword</PASSWORD>' +
                    '</s:Header>' +
                    '<s:Body>' +
                        '<GetData>Foo</GetData>' +
                    '</s:Body>' +
                '</s:Envelope>';            


            // Send the POST request
            xmlhttp.setRequestHeader('Content-Type', 'text/xml');
            xmlhttp.setRequestHeader('SOAPAction', 'http://tempuri.org/MySoapActionURL');
            xmlhttp.send(sr);


            // The following XPath query should fetch the <GetResponse> element from the SOAP XML Response 
            var query = "//ns1:GetResponse[1]"; 

            // Object defining namespaces in the query 
            var namespaceMapping = { 
            ns1:  "http://tempuri.org/",  // SOAP namespace 
            diffgr: "urn:schemas-microsoft-com" // service-specific namespace 
            }; 

            // Extract the <GetResponse> element from the response document 
            var responseNode=XML.getNode(XMLHttpRequest.responseXML, query, namespaceMapping);

            return responseNode;

        }

            window.onload = soap;

    </script>
</head>
<body>
</body>
<html>

Your assistance would be highly appreciated. Thank you for your attention.

Answer №1

To fetch data from the server, you can utilize the evaluate method on the responseXML:


	var request = new XMLHttpRequest();
	request.open('POST', 'https://mysoapurl.com', true);

	// Constructing SOAP request
	var soapRequest =
		'<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">' +
			'<s:Header> ' +
				'<USERNAME xmlns="http://www.tempuri.org">MyUsername</USERNAME>' +
				'<PASSWORD xmlns="http://www.tempuri.org">MyPassword</PASSWORD>' +
			'</s:Header>' +
			'<s:Body>' +
				'<GetData>Foo</GetData>' +
			'</s:Body>' +
		'</s:Envelope>';            

	// Sending the POST request
	request.setRequestHeader('Content-Type', 'text/xml');
	request.setRequestHeader('SOAPAction', 'http://tempuri.org/MySoapActionURL');
	
	request.onload = function(event) {
		var doc = this.responseXML;
		var namespaceMappings = { 
			ns1: "http://tempuri.org/",   
			diffgr: "urn:schemas-microsoft-com" 
		}; 
		
		var node = doc.evaluate('//ns1:GetResponse[1]', doc, 
			function(prefix) {
				return namespaceMappings[prefix];
			},
			XPathResult.FIRST_ORDERED_NODE_TYPE,
			null).singleNodeValue;

		if (node != null) {
			// You can now access node.textContent and perform further operations.
		}
	};
	
	request.send(soapRequest);

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

"JavaScript error: The function is not defined" encountered when utilizing noobslider and mootools

Hello everyone, I am relatively new to Javascript and recently encountered an issue while trying to use a Slider called noobSlide (mootools). Initially, I was successful in implementing it, but on my second attempt, I faced some difficulties. The error me ...

The RxJs Observer connected to a websocket only triggers for a single subscriber

Currently, I am encapsulating a websocket within an RxJS observable in the following manner: this.wsObserver = Observable.create(observer=>{ this.websocket.onmessage = (evt) => { console.info("ws.onmessage: " + evt); ...

Guide on embedding PHP code into a HTML div element using JQuery

I am having trouble loading PHP code into a div tag to display the results. The code I have listed below does not seem to work for me. If anyone can offer assistance in resolving this issue, I would greatly appreciate it. Here is the code snippet: <h ...

Tips for adjusting text color in a paragraph based on its content

I have a paragraph or h1 with phrases like "the color of this item is Magenta" or "this output is Red". These color-specific words (red, black, cyan, magenta or yellow) may appear within the paragraph or h1 tag. Here is my current code snippet: HTML < ...

Error in retrieving information from the worldweatheronline API

I have been attempting to retrieve weather information from 'worldweatheronline' by making an $http call in an angular factory: this.testApi = function(coords) { var deferred = $q.defer(); $http.jsonp(API_ROOTS + '?key=9834 ...

creating curved lines in three.js

I'm looking for assistance in creating a globe using three.js where I can project arcs representing exports and imports between countries. I have a basic globe set up, but I need guidance on the following: 1. How to use country shape files instead of ...

Before starting the operation, the beforeEach() function in the asynchronous Jasmine test is not being called

I'm currently coding a test for my client-server modules. One challenge I'm facing is that I need to ensure the server is running before the client sends its requests. To achieve this, I am attempting to utilize the beforeEach method. However, th ...

Which RxJS operators necessitate unsubscription?

It can be confusing to know which operators in RxJS must be unsubscribed from to prevent subscription leaks. Some, like forkJoin, complete automatically, while others, such as combineLatest, never complete. Is there a comprehensive list or guideline availa ...

PHP script encountering difficulty inserting data into database when AJAX is utilized; functions flawlessly without AJAX

In my "user registration" file, there is a form with the following structure: <form action="" method="POST"> <label for="user" class="control-label">User </label> <input type="text" name="user" class="form-control" id="user" ...

Having trouble with D3.js Tooltip not showing up when mousing over elements?

I am working on a project involving a map of Kansas City that includes data on the number of crimes in each neighborhood. My goal is to add a tooltip that displays this crime data when hovering over each district. Here is how I have set it up so far: var ...

Indicate specific colors for every link within a force-directed network using networkD3::forceNetwork()

How can we assign different colors to links based on their weight using the networkD3::forceNetwork function in R? For example, using the color Blue for links with a weight greater than 1 and dark for links with a weight less than 1. Here is an example co ...

Angular.js can dynamically add a class to an element based on the current page being viewed

Currently, my goal is to assign the class post to my div with id #wrap when I am on the page /post. Here's what I have so far: $routeProvider when('/post', { templateUrl : 'views/post.php', controller : 'postCtrl&ap ...

Expanding URL path parameters in Angular's ui-routerWould you like to

Can UI-router handle this type of routing? Parent state - /saved/:id Child state - /saved/:id/eat Here is the code snippet I am using. However, when I attempt to access it, the page redirects: .state('fruits.banana.saved', { url: &apo ...

Combine items based on their keys and corresponding values

The original question has been updated for clarity. The desired output is to merge an array of objects into a single object with specific conditions. I am attempting to consolidate three sets of keys per object into one instance, choosing the lowest numbe ...

Add the item to a fresh array using the Ajax function

Here is an array that I have: var arrayOfResults = []; // Results after like statement After making a database call, I receive a JSON result like this: [{ "id": "{fcb42c9c-3617-4048-b2a0-2600775a4c34}", "pid": "{34214CCB-90C3-4D ...

My attempt at creating a straightforward sorting function turned out to be ineffective

My attempt at creating a basic sorting function seems to be failing as it is still returning the original list instead of the sorted one. function sortByPopular (collection) { let items = collection.slice(); items.sort(function(a,b) { re ...

"Troubleshooting: Issue with ng-click in AngularJS not triggering ng-show

I can't figure out why my ng-click isn't showing the ng-show message. I've tried searching for a solution but no luck. Here is my controller function: $scope.showLogoutMessage = function() { $scope.logoutmsg = true; }; This is my Logi ...

I have a task to create a program that can extract unique elements from an existing array and add them to a new array

I am in the process of creating a code snippet that will extract unique elements from an array and store them in a new array. My approach involves developing two custom functions, similar to .includes and .push. The arrIncludesTest function is designed to ...

Exploring Amcharts using detailed JSON data

[{"SUM_PTS":{"datatype":"INTEGER","length":"8","value":"29903727","obfuscated":"false"},"SUM_TOTAL":{"datatype":"INTEGER","length":"10","value":"1644704985","obfuscated":"false"},"MID":{"datatype":"ALPHANUMERIC","length":"27","value":"Vendor 1","obfuscated ...

Tips for concealing scrollbars across various browsers without compromising functionality

Is there a way to hide the scrollbar functionality on a horizontal scrollbar without using "overflow: hidden"? I need to maintain JS functionality and ensure compatibility with all modern browsers. $j = jQuery.noConflict(); var $panels = $j('#primar ...