SharePoint newListItem Soap with img attachment - javascript

I have a function in my Apache Cordova application to create a new list item inside a sharepoint list, and I was wondering if it was possible to add an image to this new item, this would come as an 'attachment' in the sharepoint list. My function to add a new item looks like this:
function CreateItem(Title, Description) {
var soapEnv =
"<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:Body>" +
"<UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">" +
"<listName>LISTNAME</listName>" +
"<updates>" +
"<Batch OnError=\"Continue\">" +
"<Method ID=\"1\" Cmd=\"New\">" +
"<Field Name=\"ID\">New</Field>" +
"<Field Name=\"Title\">" + Title + "</Field>" +
"<Field Name=\"Description\">" + Description + "</Field>" +
"</Method>" +
"</Batch>" +
"</updates>" +
"</UpdateListItems>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
$.ajax({
url: "URL",
type: "POST",
dataType: "xml",
data: soapEnv,
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction",
"http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
},
complete: processCreateResultSuccess,
contentType: "text/xml; charset=\"utf-8\"",
error: processCreateResultError
});
}
The image is taken with the Cordova app and has the ID "image". Any thoughts?

SharePoint: AddAttachment SOAP Web Service
Yes, you can use SharePoint SOAP web services to upload an image attachment to a list. However, there are some limitations.
My demo below uses the AddAttachment action of the Lists web service. The required parameters are listed and can be modified for your own environment. The demo simply adds a text file attachment, but it works with images and other file types too. Also works with SP 2007-2013.
The limitation is that files must be encoded as base-64 for transfer within the SOAP envelope. On the client side, base-64 file encoding is not a trivial task. I've done it using the FileReader object, but that is only available in modern browsers (IE10). There might be other options with mobile devices, but I've not researched it. Alternatively, you might look at the newer REST API.
<html>
<body>
<script type='text/javascript'>
function addAttachment( ) {
var webUrl = '', // base url when list in sub site
listName = 'CustomList', // list name or guid
listItemID = '1', // list item id
fileName = 'HelloWorld.txt', // file name
attachment = 'SGVsbG8gV29ybGQ=', // base-64 encode file data "Hello Word!"
xhr, soap;
soap = (
'<?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>'+
'<AddAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/">'+
'<listName>' + listName + '</listName>'+
'<listItemID>' + listItemID + '</listItemID>'+
'<fileName>' + fileName + '</fileName>'+
'<attachment>' + attachment + '</attachment>'+
'</AddAttachment>'+
'</soap:Body>'+
'</soap:Envelope>'
);
xhr = new XMLHttpRequest();
xhr.open( 'POST', webUrl + '/_vti_bin/Lists.asmx', true );
xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xhr.setRequestHeader('SOAPAction', 'http://schemas.microsoft.com/sharepoint/soap/AddAttachment');
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
// do something - returns file path or error message
console.info( xhr.status + '\n' + xhr.responseText );
}
xhr.send( soap );
}
</script>
</body>
</html>

Related

jQuery sends OPTIONS instead of POST request to REST on localhost

I am trying to send a form thru POST to my REST Resource (Java) and I am not able to, as my request gets sent as OPTIONS instead. I Know that the REST Resource is fine since it works perfectly while I test it with Poster Firefox.
jQuery/Ajax call:
function loadTwitter(){
arrayTweets = new Array();
var urlTwitter = "http://localhost:8081/streamingvideoservice/services/twitter/retrieveTweets";
$.ajax({
type: "POST",
url: urlTwitter,
contentType: "application/x-www-form-urlencoded",
//accept: "application/json",
data: $("form#mapForm").serialize(),
dataType: "json",
async: false,
success: function (resp, status, xhr) {
$("#message").html("STATUS: " + xhr.status + " " + xhr.statusText + "\n" + resp);
$("#message").hide();
$.each(resp, function() {
$.each(this, function(i, item) {
arrayTweets.push(item);
});
});
displayTweets();
},
error: function(resp, status, xhr){
$("#message").html("ERROR: " + xhr.status + " " + xhr.statusText + "\n" + resp.e);
$("#message").show();
}
});
}
REST Resource:
#POST
#Path("/retrieveTweets")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces("application/json")
public List<Tweet> retrieve(#FormParam("lat") Double Latitude, #FormParam("lon") Double Longitude, #FormParam("rad") Integer Radius, #FormParam("from") String From, #FormParam("to") String To) {
ArrayList<Tweet> lTweets = new ArrayList<Tweet>();
boolean status = false;
Twitter twitter = new TwitterFactory().getInstance();
AccessToken accessToken = new AccessToken(TwitterInterface.ACCESS_TOKEN, TwitterInterface.ACCESS_TOKEN_SECRET);
twitter.setOAuthConsumer(TwitterInterface.CONSUMER_KEY, TwitterInterface.CONSUMER_SECRET);
twitter.setOAuthAccessToken(accessToken);
try {
Query query = new Query("");
GeoLocation geo = new GeoLocation(Latitude, Longitude);
query.setGeoCode(geo, Radius, Query.KILOMETERS);
query.setCount(100);
query.setSince(From);
query.setUntil(To);
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
Tweet t = new Tweet();
t.setUser(tweet.getUser().getScreenName());
t.setText(tweet.getText());
lTweets.add(t);
}
}
catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
return lTweets;
}
I am using jQuery 1.9.1 and hosting the Resource on Tomcat 6.
Any help is appreciated.
Thanks in advance.
You appear to be making a cross origin Ajax request. This requires that the server provides an Access-Control-Allow-Origin header to grant permission to the site hosting the page containing the JS to read the data.
Something about the request (probably the X-Requested-With header that jQuery adds to Ajax requests) is triggering a preflight request which uses an OPTIONS request to ask the server for permission before making the main request.
You will need to configure the server to provide an OPTIONS response with suitable Access Control headers as per the CORS specification (linked above).
Solved it with a GET instead and passing the parameters in the URI.

How to consume soap web service (.asmx) secure by basic authentication using jQuery?

I am trying to call a (.asmx) soap web service that require basic authentication using jQuery (or anything that would work).
And how to pass parameters to the (.asmx) soap web service
I've not been able to come up with any answers on Google. Is it possible?
OK, Finally I was able to resolve this issue :)
I was searching in the wrong direction, I was looking how to open the URL secured by basic authentication using $.Ajax, where I should search for consuming SOAP service from JavaScript using XMLHttpRequest()
the following is the answer to my question:
var symbol = "MSFT";
var xmlhttp = new XMLHttpRequest();
//xmlhttp.open("POST", "http://www.webservicex.net/stockquote.asmx?op=GetQuote", true);
// if you use username and password to secure your URL
xmlhttp.open("POST", "http://www.webservicex.net/stockquote.asmx?op=GetQuote", true, 'username', 'password');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
console.log(xmlhttp.responseText);
}
}
xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml = '<?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> ' +
'<GetQuote xmlns="http://www.webserviceX.NET/"> ' +
'<symbol>' + symbol + '</symbol> ' +
'</GetQuote> ' +
'</soap:Body> ' +
'</soap:Envelope>';
xmlhttp.send(xml);
You need to use jquery ajax for that.
var uri="http://asmx_file_path/asmx_service_file_name/method_name_in_asmx_file"
//ex: var uri = "http://mysite.test.com/services/data/mobile.asmx?method=login&username=" + uname+ "&password=" + pwd;
$.ajax({
type: "GET",
url: uri,
success: function (msg) {
jasondata = eval('(' + msg + ')');
},
});
You also need to add service reference for that asmx file.
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Services>
<asp:ServiceReference Path="~/services/data/mobile.asmx" />
</Services>
</asp:ScriptManagerProxy>
You can have a look at this tutorial.
calling-asmx-web-service-via-jquery-ajax

Is there any size limitation for ajax post?

I'm posting ckeditor content via Ajax to php. But getting 4-5 sentence of posted material in my db table. I wonder, Is there any size limitation for ajax post? is there any way to post big text contents via ajax?
My js looks like that
function postViaAjax(autosaveMode) {
var name = $("#name").val();
var title = $("#title").val();
var menu = $("#menu").val();
var parentcheck = $(".parentcheck:checked").val();
var id = $("#id").val();
if (parentcheck == 0) {
var parent = parentcheck;
} else {
var parent = $("#parent").val();
}
var content = CKEDITOR.instances['content'].getData();
var dataString = 'name=' + name + '&title=' + title + '&menu=' + menu + '&parentcheck=' + parentcheck + '&id=' + id + '&parent=' + parent + '&content=' + content;
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
var message = result.msg;
var err = result.err;
var now = new Date();
if (message != null) {
if (autosaveMode) {
$('#submit_btn').attr({
'value': 'Yadda saxlanıldı ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
} else {
$.notifyBar({
cls: "success",
html: message + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
}
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
}
});
};
The HTTP specification doesn't impose a specific size limit for posts. They will usually be limited by either the web server or the programming technology used to process the form submission.
What kind of server do you use?
There isn't any size limitation for POSTs in HTTP.
Maybe you have an & in your content variable. Then everything after that would be stripped after that.
Other than that what type do you use for your data column in the database? Is it, by any chance, something like varchar(1000)? Then anything bigger would also get stripped.
Check what you actually receive on the server end, so you know if you've got a problem with the code or the database.
You have a limitation on the Apache server. Look for LimitRequestBody directive.
This may be helpful:
http://gallery.menalto.com/node/14870
In theory the limits on AJAX requests are the same on all the other requests, so it depends on your web server/app setup. See also Max length of send() data param on XMLHttpRequest Post

xmlhttprequest POST method in rails

In the web, I'm building local file drag and drop upload to the server with the ruby on rails, dragging and drop a file working fine, but how to get the dragged file content in the controller with the drop event? I'm getting the file with event.datatransfer, send file through Javascript with XMLHttpRequest.
function handleDrop(event)
{
preventDef(event)
var dt = event.dataTransfer;
var files = dt.files;
for(var i = 0; i < files.length;i++)
{
http_request = new XMLHttpRequest();
var boundaryString = 'the_boundery--';
var boundary = '--' + boundaryString;
var requestbody = boundary + '\n'
+ 'Content-Disposition: form-data; name="thefilename"' + '\n'
+ '\n'
+ files[i].fileName + '\n'
+ '\n'
+ boundary + '\n'
+ 'Content-Disposition: form-data; name="thefile"; filename="'
+ files[i].fileName + '"' + '\n'
+ 'Content-Type: application/octet-stream' + '\n'
+ '\n'+files[i].path
+'\n'+ files[i].getAsBinary()
+ '\n'
+ boundary;
var preview = document.getElementById("preview");
preview.src = files[i].getAsDataURL();
var queryString="";
queryString="filename="+files[i].fileName+'&'+"file_to_upload=="+files[i].getAsBinary();
var actionUrl="/shortening/dr";
http_request.open('POST',actionUrl,true);
http_request.setRequestHeader("Content-type", "multipart/form-data; \
boundary=\"" + boundaryString + "\"");
http_request.setRequestHeader("Connection", "close");
http_request.setRequestHeader("Content-length", requestbody.length);
http_request.sendAsBinary(requestbody);
}
}
using this script calling the url and send the file through sendAsBinary method
Post method not calling the controller with the respective action
How to get the requestbody in the controller ?
Any idea?
First off, use some kind of javascript library to do AJAX and pretty much everything else. I'd suggest jQuery (http://jquery.com/)
Unfortunatelly no browser supports file uploads through XmlHttpRequest.
Read sometime ago something about Firefox supporting it, but that would be restricting and I'm not even sure that really works.
You could make an iframe and with the drop event, set the file field inside the iframe and then submit the iframe.

Simplest SOAP example

What is the simplest SOAP example using Javascript?
To be as useful as possible, the answer should:
Be functional (in other words actually work)
Send at least one parameter that can be set elsewhere in the code
Process at least one result value that can be read elsewhere in the code
Work with most modern browser versions
Be as clear and as short as possible, without using an external library
This is the simplest JavaScript SOAP Client I can create.
<html>
<head>
<title>SOAP JavaScript Client Test</title>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://somesoapurl.com/', true);
// build SOAP request
var sr =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soapenv:Envelope ' +
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soapenv:Body>' +
'<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<username xsi:type="xsd:string">login_username</username>' +
'<password xsi:type="xsd:string">password</password>' +
'</api:some_api_call>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
// alert('done. use firebug/console to see network response');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// ...
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" value="Soap" onclick="soap();" />
</div>
</form>
</body>
</html> <!-- typo -->
There are many quirks in the way browsers handle XMLHttpRequest, this JS code will work across all browsers:
https://github.com/ilinsky/xmlhttprequest
This JS code converts XML into easy to use JavaScript objects:
http://www.terracoder.com/index.php/xml-objectifier
The JS code above can be included in the page to meet your no external library requirement.
var symbol = "MSFT";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://www.webservicex.net/stockquote.asmx?op=GetQuote",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
// http://www.terracoder.com convert XML to JSON
var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text;
// Result text is escaped XML string, convert string to XML object then convert to JSON object
json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result));
alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text);
}
}
xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml = '<?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> ' +
'<GetQuote xmlns="http://www.webserviceX.NET/"> ' +
'<symbol>' + symbol + '</symbol> ' +
'</GetQuote> ' +
'</soap:Body> ' +
'</soap:Envelope>';
xmlhttp.send(xml);
// ...Include Google and Terracoder JS code here...
Two other options:
JavaScript SOAP client:
http://www.guru4.net/articoli/javascript-soap-client/en/
Generate JavaScript from a WSDL:
https://cwiki.apache.org/confluence/display/CXF20DOC/WSDL+to+Javascript
This cannot be done with straight JavaScript unless the web service is on the same domain as your page. Edit: In 2008 and in IE<10 this cannot be done with straight javascript unless the service is on the same domain as your page.
If the web service is on another domain [and you have to support IE<10] then you will have to use a proxy page on your own domain that will retrieve the results and return them to you. If you do not need old IE support then you need to add CORS support to your service. In either case, you should use something like the lib that timyates suggested because you do not want to have to parse the results yourself.
If the web service is on your own domain then don't use SOAP. There is no good reason to do so. If the web service is on your own domain then modify it so that it can return JSON and save yourself the trouble of dealing with all the hassles that come with SOAP.
Short answer is: Don't make SOAP requests from javascript. Use a web service to request data from another domain, and if you do that then parse the results on the server-side and return them in a js friendly form.
You can use the jquery.soap plugin to do the work for you.
This script uses $.ajax to send a SOAPEnvelope. It can take XML DOM, XML string or JSON as input and the response can be returned as either XML DOM, XML string or JSON too.
Example usage from the site:
$.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
}
});
Has anyone tried this? https://github.com/doedje/jquery.soap
Seems very easy to implement.
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>
Thomas:
JSON is preferred for front end use because we have easy lookups. Therefore you have no XML to deal with. SOAP is a pain without using a library because of this. Somebody mentioned SOAPClient, which is a good library, we started with it for our project. However it had some limitations and we had to rewrite large chunks of it. It's been released as SOAPjs and supports passing complex objects to the server, and includes some sample proxy code to consume services from other domains.
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
var wsUrl = "http://abc.com/services/soap/server1.php";
var soapRequest ='<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> <getQuote xmlns:impl="http://abc.com/services/soap/server1.php"> <symbol>' + $("#txtName").val() + '</symbol> </getQuote> </soap:Body></soap:Envelope>';
alert(soapRequest)
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml",
dataType: "xml",
data: soapRequest,
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) { alert('success');
if (status == "success")
$("#response").text($(req.responseXML).find("Result").text());
alert(req.responseXML);
}
function processError(data, status, req) {
alert('err'+data.state);
//alert(req.responseText + " " + status);
}
</script>
</head>
<body>
<h3>
Calling Web Services with jQuery/AJAX
</h3>
Enter your name:
<input id="txtName" type="text" />
<input id="btnCallWebService" value="Call web service" type="button" />
<div id="response" ></div>
</body>
</html>
Hear is best JavaScript with SOAP tutorial with example.
http://www.codeproject.com/Articles/12816/JavaScript-SOAP-Client
Easily consume SOAP Web services with JavaScript -> Listing B
function fncAddTwoIntegers(a, b)
{
varoXmlHttp = new XMLHttpRequest();
oXmlHttp.open("POST",
"http://localhost/Develop.NET/Home.Develop.WebServices/SimpleService.asmx'",
false);
oXmlHttp.setRequestHeader("Content-Type", "text/xml");
oXmlHttp.setRequestHeader("SOAPAction", "http://tempuri.org/AddTwoIntegers");
oXmlHttp.send(" \
<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> \
<AddTwoIntegers xmlns='http://tempuri.org/'> \
<IntegerOne>" + a + "</IntegerOne> \
<IntegerTwo>" + b + "</IntegerTwo> \
</AddTwoIntegers> \
</soap:Body> \
</soap:Envelope> \
");
return oXmlHttp.responseXML.selectSingleNode("//AddTwoIntegersResult").text;
}
This may not meet all your requirements but it is a start at actually answering your question. (I switched XMLHttpRequest() for ActiveXObject("MSXML2.XMLHTTP")).
Some great examples (and a ready-made JavaScript SOAP client!) here:
http://plugins.jquery.com/soap/
Check the readme, and beware the same-origin browser restriction.
The question is 'What is the simplest SOAP example using Javascript?'
This answer is of an example in the Node.js environment, rather than a browser. (Let's name the script soap-node.js) And we will use the public SOAP web service from Europe PMC as an example to get the reference list of an article.
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const DOMParser = require('xmldom').DOMParser;
function parseXml(text) {
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(text, "text/xml");
Array.from(xmlDoc.getElementsByTagName("reference")).forEach(function (item) {
console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);
});
}
function soapRequest(url, payload) {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', url, true);
// build SOAP request
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
parseXml(xmlhttp.responseText);
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(payload);
}
soapRequest('https://www.ebi.ac.uk/europepmc/webservices/soap',
`<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header />
<S:Body>
<ns4:getReferences xmlns:ns4="http://webservice.cdb.ebi.ac.uk/"
xmlns:ns2="http://www.scholix.org"
xmlns:ns3="https://www.europepmc.org/data">
<id>C7886</id>
<source>CTX</source>
<offSet>0</offSet>
<pageSize>25</pageSize>
<email>ukpmc-phase3-wp2b---do-not-reply#europepmc.org</email>
</ns4:getReferences>
</S:Body>
</S:Envelope>`);
Before running the code, you need to install two packages:
npm install xmlhttprequest
npm install xmldom
Now you can run the code:
node soap-node.js
And you'll see the output as below:
Title: Perspective: Sustaining the big-data ecosystem.
Title: Making proteomics data accessible and reusable: current state of proteomics databases and repositories.
Title: ProteomeXchange provides globally coordinated proteomics data submission and dissemination.
Title: Toward effective software solutions for big biology.
Title: The NIH Big Data to Knowledge (BD2K) initiative.
Title: Database resources of the National Center for Biotechnology Information.
Title: Europe PMC: a full-text literature database for the life sciences and platform for innovation.
Title: Bio-ontologies-fast and furious.
Title: BioPortal: ontologies and integrated data resources at the click of a mouse.
Title: PubMed related articles: a probabilistic topic-based model for content similarity.
Title: High-Impact Articles-Citations, Downloads, and Altmetric Score.
Simplest example would consist of:
Getting user input.
Composing XML SOAP message similar to this
<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>
<GetInfoByZIP xmlns="http://www.webserviceX.NET">
<USZip>string</USZip>
</GetInfoByZIP>
</soap:Body>
</soap:Envelope>
POSTing message to webservice url using XHR
Parsing webservice's XML SOAP response similar to this
<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>
<GetInfoByZIPResponse xmlns="http://www.webserviceX.NET">
<GetInfoByZIPResult>
<NewDataSet xmlns="">
<Table>
<CITY>...</CITY>
<STATE>...</STATE>
<ZIP>...</ZIP>
<AREA_CODE>...</AREA_CODE>
<TIME_ZONE>...</TIME_ZONE>
</Table>
</NewDataSet>
</GetInfoByZIPResult>
</GetInfoByZIPResponse>
</soap:Body>
</soap:Envelope>
Presenting results to user.
But it's a lot of hassle without external JavaScript libraries.
function SoapQuery(){
var namespace = "http://tempuri.org/";
var site = "http://server.com/Service.asmx";
var xmlhttp = new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
xmlhttp.setOption(2, 13056 ); /* if use standard proxy */
var args,fname = arguments.callee.caller.toString().match(/ ([^\(]+)/)[1]; /*Имя вызвавшей ф-ции*/
try { args = arguments.callee.caller.arguments.callee.toString().match(/\(([^\)]+)/)[1].split(",");
} catch (e) { args = Array();};
xmlhttp.open('POST',site,true);
var i, ret = "", q = '<?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><'+fname+ ' xmlns="'+namespace+'">';
for (i=0;i<args.length;i++) q += "<" + args[i] + ">" + arguments.callee.caller.arguments[i] + "</" + args[i] + ">";
q += '</'+fname+'></soap:Body></soap:Envelope>';
// Send the POST request
xmlhttp.setRequestHeader("MessageType","CALL");
xmlhttp.setRequestHeader("SOAPAction",namespace + fname);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
//WScript.Echo("Запрос XML:" + q);
xmlhttp.send(q);
if (xmlhttp.waitForResponse(5000)) ret = xmlhttp.responseText;
return ret;
};
function GetForm(prefix,post_vars){return SoapQuery();};
function SendOrder2(guid,order,fio,phone,mail){return SoapQuery();};
function SendOrder(guid,post_vars){return SoapQuery();};
Angularjs $http wrap base on XMLHttpRequest. As long as at the header content set following code will do.
"Content-Type": "text/xml; charset=utf-8"
For example:
function callSoap(){
var url = "http://www.webservicex.com/stockquote.asmx";
var soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://www.webserviceX.NET/\"> "+
"<soapenv:Header/> "+
"<soapenv:Body> "+
"<web:GetQuote> "+
"<web:symbol></web:symbol> "+
"</web:GetQuote> "+
"</soapenv:Body> "+
"</soapenv:Envelope> ";
return $http({
url: url,
method: "POST",
data: soapXml,
headers: {
"Content-Type": "text/xml; charset=utf-8"
}
})
.then(callSoapComplete)
.catch(function(message){
return message;
});
function callSoapComplete(data, status, headers, config) {
// Convert to JSON Ojbect from xml
// var x2js = new X2JS();
// var str2json = x2js.xml_str2json(data.data);
// return str2json;
return data.data;
}
}

Categories