Calling Web Service using Javascript with a SOAP envelope fails - javascript

I try to access from a browser a simple mailing list service I developed. I adapted a working example I found but I don't know why the request doesn't seem to reach the service and so no response is returned.
Using a SOAP envelope is a requirement, I need to know what is possibly wrong with this code, not how I could do the same thing using other techniques. (The service is deployed correctly on a GlassFish server and I have a working Java client to test it, so no problem with the service)
Does anyone see something bad (I'm joining the WSDL too, if you need any other detail don't hesitate)? Thanks!
<html>
<head>
<title>Soap Invocation</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var request = null;
function createRequest() {
if (window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else{
if (new ActiveXObject("Microsoft.XMLHTTP")) {
request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request = new ActiveXObject("Msxml2.XMLHTTP");
}
}
}
function getMail() {
createRequest();
var envelope = "<?xml version='1.0' encoding='UTF-8'?>";
envelope += "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
envelope += "<soap:Header/>";
envelope += "<soap:Body>";
envelope += "<ns2:getMails xmlns:ns2='http://service.inf4375.com/'>";
envelope += "</ns2:getMails>";
envelope += "</soap:Body>";
envelope += "</soap:Envelope>";
var url = "http://127.0.0.1:8080/SoapService/MailingService";
request.onreadystatechange = updatePage;
request.open("GET", url, false);
request.setRequestHeader("Content-Type", "text/html");
request.setRequestHeader("SOAPAction", "");
request.send(envelope);
}
function updatePage() {
if(request.readyState == 4) {
document.getElementById("get").innerHTML = "<p>" + request.responseXML.selectSingleNode("//return").text + "</p>";
} else {
document.getElementById("get").innerHTML = "Loading..."
}
}
</script>
</head>
<body>
<input type="button" value="GetMail" onclick="getMail();" />
<span id="get"></span>
</body>
</html>
The WSDL :
<?xml version='1.0' encoding='UTF-8'?>
<definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://service.inf4375.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://service.inf4375.com/" name="MailingService">
<types>
<xsd:schema>
<xsd:import namespace="http://service.inf4375.com/" schemaLocation="http://localhost:8080/SoapService/MailingService?xsd=1"/>
</xsd:schema>
</types>
<message name="getMails">
<part name="parameters" element="tns:getMails"/>
</message>
<message name="getMailsResponse">
<part name="parameters" element="tns:getMailsResponse"/>
</message>
<message name="addMail">
<part name="parameters" element="tns:addMail"/>
</message>
<message name="addMailResponse">
<part name="parameters" element="tns:addMailResponse"/>
</message>
<portType name="Mailing">
<operation name="getMails">
<input wsam:Action="http://service.inf4375.com/Mailing/getMailsRequest" message="tns:getMails"/>
<output wsam:Action="http://service.inf4375.com/Mailing/getMailsResponse" message="tns:getMailsResponse"/>
</operation>
<operation name="addMail">
<input wsam:Action="http://service.inf4375.com/Mailing/addMailRequest" message="tns:addMail"/>
<output wsam:Action="http://service.inf4375.com/Mailing/addMailResponse" message="tns:addMailResponse"/>
</operation>
</portType>
<binding name="MailingPortBinding" type="tns:Mailing">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="getMails">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="addMail">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="MailingService">
<port name="MailingPort" binding="tns:MailingPortBinding">
<soap:address location="http://localhost:8080/SoapService/MailingService"/>
</port>
</service>
I don't get any errors in the Error Console when I'm trying to execute it on Firefox, and Internet Explorer is only displaying the Loading... and nothing more.

SOAP must be sent via a POST, not a GET.
Also, it looks like your WS-Messaging headers are wrong. In fact, I don't even see them.
Try issuing this call using a .NET client ("Add Service Reference"), and watch on the wire with Fiddler or something like it to see what's happening. Then do the same thing.

Related

HTML Form Input Fields to read and write XML file

I am currently trying to build an HTML form with input fields to read an XML file and write back with changes. The first step is retrieving values on page load into the input fields but it doesn't want to work
<body>
<h1>Config Page</h1>
<div>
<b>Site URL:</b> <input type="text" id="siteURL" value="site..."/></span><br>
<b>Site Collection:</b> <span id="siteCollection"></span><br>
</div>
<script>
var xmlhttp, xmlDoc;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Configuration/config.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElement
document.getElementById("siteURL").value.innerHTML =
xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue;
document.getElementById("siteCollection").innerHTML =
xmlDoc.getElementsByTagName("siteCollection")[0].childNodes[0].nodeValue;
function myFunction() {
alert(siteURL + "is the site Url")
}
</script>
<button onclick="myFunction()">Get message value</button>
I know the XML is pulling through ok because the siteCollection span item works, but the input field does not.
Any help would be much appreciated.
Thank you.
Maybe if you use jQuery you can do it as following
http://codepen.io/Daethe/pen/dXWjJo
<div>
<b>Site URL:</b> <input type="text" id="siteURL" value="site..."/></span><br>
</div>
<button onclick="myFunction()">Get message value</button>
<script>
function myFunction() {
var xmlHttp = jQuery.parseXML('<?xml version="1.0" encoding="utf-8"?><config><siteURL>http://localhost/</siteURL></config>');
var xmlDoc;
xmlDoc = xmlHttp.documentElement;
$("#siteURL").val(xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue);
}
</script>
Thanks to Daethe for putting me on the right track. I found my solution to read an xml file into a HTML input field form
for the javascript...
var xmlpath = "../configuration/test.xml"
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlpath, false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
function loadFunction() {
$("#siteURL").val(xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue);
}
For the page...
<script src="/Script/form.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<html>
<br>Site URL (EG: http://intranet)</br>
<input type="text" id="siteURL" name="siteURL" value="blank..." />
<button onclick="loadFunction()">Load Configuration</button>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<title>Please Check Data</title>
<script type="text/javascript">
function readXMLFile() {
var i;
var xml = new XMLHttpRequest();
xml.open('GET', 'projectRelatedData.xml', false);
xml.send();
var xmlData = xml.responseXML;
xmlData=(new DOMParser()).parseFromString(xml.responseText,'text/xml');
var projectData=xmlData.getElementsByTagName("project");
//alert(projectData.length);
for(i=0;i<projectData.length;i++)
{
var name=projectData[i].getElementsByTagName("name")[0].firstChild.data;
var imageName=projectData[i].getElementsByTagName("imagePath")[0].firstChild.data;
var pdfName=projectData[i].getElementsByTagName("pdfPath")[0].firstChild.data;
var description=projectData[i].getElementsByTagName("description")[0].firstChild.data;
var amount=projectData[i].getElementsByTagName("amount")[0].firstChild.data;
//alert("number of Project : "+projectData.length);
document.write(name+'<br>');
document.write(imageName+'<br>');
document.write(pdfName+'<br>');
document.write(description+'<br>');
document.write(amount+'<br>');
}
}
</script>
</head>
<body>
<button onclick="readXMLFile()">Click</button>
<p id="ccc"></p>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<projectWebsite>
<project>
<name>CARGO SHIPPING</name>
<imagePath>CARGOSHIPPING.PNG</imagePath>
<pdfPath>cargoShipping.pdf</pdfPath>
<description>
Cargo shipping is all about booking cargo to move from one place to another. Owner can add new shipsand he can also track ships.User can register for cargo and he can also track ships.Admin has the right to view detailsof owner, to add a new company and also update price of ship. This software hasa very nice GUI to give a very nice presentation of a cargo management system.
</description>
<amount>4000</amount>
</project>
<project>
<name>E-BAZZAR</name>
<imagePath>ebazzar.PNG</imagePath>
<pdfPath>eBazar.pdf</pdfPath>
<description>
This project emphasizes on taking bookings of pat ient in a web portal system.Patient can search for the doctor and book for appointment . Doctor can check and confirm appointment so patient can visit accordingly.Also admin is provided to add doctors in the portal,moreover customer list can be seen as well.
</description>
<amount>4000</amount>
</project>
</projectWebsite>

XSLT 2.0 error handling: throw exception to javascript

I have an input XML File:
<Items>
<Item Name="1" Value="Value1"></Item>
<Item Name="2" Value="Value2"></Item>
</Items>
What I want to transform to following output file with Saxon-CE.
<Items>
<Item Name="1" Value="NewValue1"></Item>
<Item Name="2" Value="NewValue2"></Item>
</Items>
JS:
function TransformXML() {
xsltData = Saxon.requestXML("transformXML.xsl");
xmlData = Saxon.requestXML("myxml.xml");
var xsltProcessor = Saxon.newXSLT20Processor(xsltData);
var result = xsltProcessor.transformToDocument(xmlData);
}
I have a mapping, that tells me the value of an item and the NewValue it should have after the transformation.
What I have so far:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*" />
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" name="xml" />
<xsl:variable name="Items">
<Item Name="1">
<Value OldValue="Value1" NewValue="NewValue1" ></Value>
</Item>
<Item Name="2">
<Value OldValue="Value2" NewValue="NewValue2" ></Value>
</Item>
</xsl:variable>
<xsl:template match="Items">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="Item">
<xsl:copy>
<xsl:if test="not($Items/Item[#Name=current()/#Name]/Value[#OldValue = current()/#Value])">
<!-- if value mismatch throw exception and stop -->
</xsl:if>
<xsl:attribute name="Value">
<xsl:value-of select="$Items/Item[#Name=current()/#Name]/Value[#OldValue = current()/#Value]/#NewValue"/>
</xsl:attribute>
<xsl:copy-of select="#*[name()!= 'Value']" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
This is working, but what I want to do now is to check if there is a value mismatch.
If yes then the script should stop and throw an exception what I can catch in the Javascript function.
Is there a way to realize this? Can I set a callback function for this?
With XSLT, you can terminate processing using <xsl:message select="'some message'" terminate="yes"/>. It would be desirable that the transformToDocument method throws a Javascript exception you could catch with try/catch but it does not seem to happen, at least not in a quick test I did. I was however able to set an error handler and handle that message in that handler, see http://home.arcor.de/martin.honnen/xslt/test2014120301.html for an example, which does
function onSaxonLoad()
{
Saxon.setLogLevel('SEVERE');
var errors = [];
Saxon.setErrorHandler(function(error) { errors.push(error); });
var xslt = Saxon.requestXML("test2014120301.xsl")
var xsltProc = Saxon.newXSLT20Processor(xslt);
xsltProc.setInitialTemplate("main");
var errorCount = errors.length;
var doc = xsltProc.transformToDocument();
if (errorCount < errors.length) {
var msg = errors[errors.length - 1].message;
var pre = document.createElement('pre');
pre.textContent = msg;
document.body.appendChild(pre);
}
else {
// use result document doc here
}
}
The message Saxon pushes to the error handler is SEVERE: XPathException in invokeTransform: Processing terminated by xsl:message in test2014120301.xsl. Obviously there could be other errors pushed to the error handler so you will need more checks on the Javascript side to perhaps check that the message test contains Processing terminated by xsl:message.

Running AJAX locally without a webserver

I have been looking for an answer for this for a month now. I am trying ro run the below script locally and getting "Access Denied" error.
Browser: IE 8
Environment: Locally, Intranet
Kindly share your thoughts on this. Thanks!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>GSDAssist</title>
<script type="text/javascript">
/***********************************************
* Dynamic Ajax Content- � Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
page_request.open('GET', url, true)
page_request.send(null)
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}
function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}
</script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<title>GSDAssist</title>
</head>
<body style>
<div id="headerBar">
<marquee id="newsTicker" behavior="scroll" direction="left"><h4>Process Updates: Tickets trashed has to be moved to DBSP RECYCLE TICKET Assignment group</h4></marquee>
</div>
<div id="main">
<div style="width:300px; height:80px; margin-left:5px; margin-bottom:10px; float:left;">
<img style="padding:5px; float:left;" src="img/logo.png" width="60" />
<h2 style="float:left; margin-left:5px;">GSDAssist</h2>
</div>
<div style="clear:both; float:left; border-bottom: 1px solid #CCCCCC;">
#
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
<br>
<br>
</div>
<div id="contentarea" style="clear:both; float:left;"><h3>Welcome to GSDAssist,</h3><p><h3>Choose the starting letter of the application to get started!</h3></div>
</div>
</body>
</html>
My thoughts on this are that it's not going to work.
XHR calls are subject to same-domain security policies (CORS is an exception, but that's almost impossible to do without controlling the server, anyway, which requires a server, which is your problem to begin with).
The point is that browsers have set security policies in place, which mean that you must request XHR data from the same domain as your browser is currently on.
file:/// is a completely different protocol than http://, and even so, browser security prevents an HTML page which is served locally from accessing file:// content in an async fashion (to prevent a page from accessing all content on your hard drive, and sending all of your data anywhere in the world).
Just about every web-centric programming language at this point has a quick-start server included (except NodeJS, but writing a simple server in Node is also very easy).
The trick would be to set a server up that's available on your intranet, without modifying the domain.

POST JSON to Jersey Service

I am trying to post some json data to REST web service implemented with Jersey framework. I am not using JAXB or jquery but only javascript.
I verified that formed json is correct but in spite of setting content type "application/json", on server it is received as "application/x-www-form-urlencoded".
Here is my code:
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = {};
var elem = document.getElementById('frmMain').elements;
//alert(elem.length);
for(var i = 0; i < elem.length-1; i++)
{
str[elem[i].name] = elem[i].value;
}
document.getElementById('lblValues').innerHTML = str;
var json = JSON.stringify(str);
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(document.getElementById('frmMain').method,
document.getElementById('frmMain').action);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Content-Length",json.length);
xhr.setRequestHeader('Accept', 'application/json');
//alert(json);
// send the collected data as JSON
xhr.send(json);
xhr.onloadend = function() {
// done
}
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain" action="/JerseyTest/rest/postUser"
method="post">
<input name="firstName" value="harry" /> <input name="lastName"
value="tester" /> <input name="toEmail" value="testtest#test.com" />
<br /> <input type="submit" value="Test"
onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
On the server side:
package com.example.jersey.test;
import javax.ws.rs.*;
#Path("/postUser")
public class JsonTest {
#POST
#Consumes("application/json")
#Produces(MediaType.TEXT_PLAIN)
public String pingPong(String json) {
return "Answer is "+ json;
}
}
I am new to web development and not sure on what I am missing in above code.
I am answering my own question for those who may visit this later. The code above is correct and works well except the fact that the url is been hit twice. First time, for submit button's default action and then as per our script by XMLHttpRequest.
This I came to know after I checked the headers in Httpfox which showed error as NS_BINDING_ABORTED.
After changing the input type to button from submit, all is working fine.

Help with parsing XML with javascript?

I am trying to use Java-script as a client for java based restful web-service. The service is a survey maker. I am having trouble getting the function to work. The server side of the service is in Google App Engine. In the code below the function uses http get to get xml representing a list of surveynames, then gets the data from the xml and puts it in a html table. The code is not working, so it would be great if some one could check it to see if I am doing this correctly or I am doing something wrong. I have never programed in javascript so I would also like to know if I need to import a library to use AJAX or is it supported by the browser?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>View Surveys</title>
</head>
<SCRIPT>
function getSurveyNames(){
var url = "http://survey-creator.appspot.com/rest/surveymakerpro/allsurveys";
var xmlhttp;
// AJAX code for Mozilla, Safari, Opera etc.
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = xmlhttpChange;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
// AJAX code for IE
else
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) {
xmlhttp.onreadystatechange = xmlhttpChange;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
HTMLSurveyNames = "<table border='1'><tr>Survey Names<th></th></tr>";
var surveyNames = xmlhttp.responseXML.documentElement.getElementsByTagName("surveys")[0];
for(var i = 0; i < surveyNames.length ;i++){
var surveyNameChildNode = surveyName[i].childNodes[0];
var name = surveyNameChildNode.nodeValue;
HTMLSurveyNames += "<tr><td>"+name+"</td></tr>";
}
//div tags
document.getElementById('displayNames').innerHTML = HTMLSurveyNames;
}
}
</SCRIPT>
<body>
<p>View Survey</p>
<form method="post">
<input name="GetSurveys" style="width: 103px" type="button" value="View all surveys" onClick=getSurveyNames(); /></form>
<p>Here Goes a Table of Surveys</p>
<div id="displayNames">
<p>Enter the survey you wish to take:</p>
<form method="post">
<input id="surveyName" name="SurveyName" style="width: 140px" type="text" value="Enter Survey Name...." /></form>
<form method="post">
<input name="Submit2" type="submit" value="Get Survey" /></form>
<div id="displaySurvey"></div>
</div>
<p>
<input id="sendtoserver" name="Submit3" type="submit" value="Submit TakenSurvey" /></p>
</body>
</html>
This is the xml I want to parse
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><surveyNames><SurveyList><surveys>DragonBallZ</surveys><surveys>FootballSurvey</surveys><surveys>NewsSurvey</surveys><surveys>PennstateSurvey</surveys></SurveyList></surveyNames>
You're sending off an asynchronous request, but then attempting to immediately process the result before this request will have finished.
You should assign a handler to xmlhttp.onreadystatechange that will be executed as your request progresses. You currently assign xmlhttpChange to this property, but you don't show what xmlhttpChange is. You should be doing something like this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// XML parsing code goes here
}
}
You do not need to import any libraries to use Ajax
Be careful with lines like HTMLSurveyNames = "<table border='1'><tr>Survey Names<th></th></tr>"; You should always use the var keyword when declaring variables, to avoid creating/modifying globals implicitly.
"<table border='1'><tr>Survey Names<th></th></tr>"
should be
"<table border='1'><tr><th>Survey Names</th></tr>"
things will work a LOT better.
there is a cross-browser XML librari for javascript at http://www.softxml.com/softxmllib/softxmllib.htm
I believe XMLHTTPRequest() is specific to IE. there are versions for other browsers. http://en.wikipedia.org/wiki/XMLHttpRequest

Categories

Resources