I try to write a simple client javascript to access to a SOAP webservice. I found an example on the web
https://thycotic.force.com/support/s/article/Using-Web-Services-with-SOAP-Javascript
and
<!DOCTYPE html>
<head>
<title>SOAP Javascript Test</title>
</head>
<body>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
//replace second argument with the path to your Secret Server webservices
xmlhttp.open('POST', 'https://URL//MANU_WSManutenzioni_MOGE/', true);
//create the SOAP request
//replace username, password (and org + domain, if necessary) with the appropriate info
var strRequest =
'<?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>' +
'<Authenticate xmlns="urn:https://URL">' +
'<IdTipologiaSegnalazione>7</IdTipologiaSegnalazione>' +
'<IdModalitaSegnalazione>6</IdModalitaSegnalazione>' +
'<IdSegnalante>21856</IdSegnalante>' +
'<Descrizione>test</Descrizione>' +
'<IdTipologiaIntervento>21</IdTipologiaIntervento>' +
'<Matricola>emergenze</Matricola>' +
'</Authenticate>' +
'</soap:Body>' +
'</soap:Envelope>';
//specify request headers
//xmlhttp.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xmlhttp.setRequestHeader('Authorization', 'TOKEN');
//FOR TESTING: display results in an alert box once the response is received
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
};
//send the SOAP request
xmlhttp.send(strRequest);
};
//build & send the request when the page loads
window.onload = function() {
soap();
};
</script>
</body>
</html>
The client seem to works but I do not understand how to send an authorization token given by the server authority.
I try with
xmlhttp.setRequestHeader('Authorization', 'TOKEN');
but it do not works
Related
I have a server running OTRS 5 and I would like to retrieve a list in XML format. I'm running a JavaScript code that should display the list, but instead I get an error.
My local server is https://labcentos3/otrs/mds.pl?Action=ServiceList.
I think its a Perl script that runs on the server side and then displays a list in XML format.
This is what I get if I browse the local link: it gives me the list I want
I wrote HTML and JavaScript to try to do the same for working with the retrieved data later, but I can't get past an error.
HTML
<html>
<head>
<title>XML read</title>
<script src="reader.js" type="text/javascript"></script>
</head>
<body>
<h1>XML File</h1><br/>
</body>
</html>
reader.js
var user = "bla bla bla";
var pass = "bla bla bla"
var getXMLFile = function(path, callback) {
var request = new XMLHttpRequest();
request.open("POST", path);
request.setRequestHeader("Content-Type", "text/plain");
//request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader('Authorization', 'Basic ' + btoa(user + ":" + pass));
request.onreadystatechange = function() {
if(request.readyState === 4 && request.status === 200) {
callback(request.responseXML);
}
};
request.send();
};
getXMLFile("https://labcentos3/otrs/mds.pl?Action=ServiceList", function(xml) {
console.log(xml);
});
The error I get in the Chrome console is this:
XMLHttpRequest cannot load https://labcentos3/otrs/mds.pl?Action=ServiceList. The request was redirected to 'https://labcentos3/otrs/index.pl', which is disallowed for cross-origin requests that require preflight.
I have very new to JS and I have done my research but I guess I'm kind of using the wrong technique or something.
Like in python to make GET request we do:
request_text = requests.get(url).text
I want to do the same thing but using JS i.e. display the content from "http://synd.cricbuzz.com/j2me/1.0/livematches.xml" in the raw(xml) format and I have found this script somewhere but it doesn't work.
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "http://synd.cricbuzz.com/j2me/1.0/livematches.xml", false);
xhttp.send();
}
</script>
</body>
</html>
I just need the direction on how to do the same i.e. how to send a GET/POST request using JS and render it on a webpage?
When I use
function test(url) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
var section = document.createElement('section');
var h2 = document.createElement('h2');
h2.textContent = 'Received from ' + url;
section.appendChild(h2);
var pre = document.createElement('pre');
pre.textContent = req.responseText;
section.appendChild(pre);
document.body.appendChild(section);
};
req.onerror = function(evt) {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '.<\/p>');
};
req.send();
}
document.addEventListener('DOMContentLoaded', function() {
test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml');
test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml');
},
false);
the first URL works as the server is set up to allow the CORS request for that directory while the second fails as the server does not allow it. So unless you serve your HTML with the script from synd.cricbuzz.com or unless you can change the configuration of synd.cricbuzz.com to allow a CORS request you won't be able to request the XML from that server.
Note also that in modern browsers (current versions of Mozilla, Chrome, Edge) you can use the Promise based fetch method instead of XMLHttpRequest, as shown below. But the same origin policy is not different for fetch, so the same as stated above holds.
function test(url) {
fetch(url).then(function(response) {
if(response.ok) {
response.text().then(function(text) {
var section = document.createElement('section');
var h2 = document.createElement('h2');
h2.textContent = 'Received from ' + url;
section.appendChild(h2);
var pre = document.createElement('pre');
pre.textContent = text;
section.appendChild(pre);
document.body.appendChild(section);
});
}
else {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '; status: ' + response.status + '.<\/p>');
}
})
.catch(function(error) {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error "' + error.message + '" requesting ' + url + '.<\/p>');
});
}
document.addEventListener('DOMContentLoaded', function() {
test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml');
test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml');
},
false);
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>
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
I'm triying to post web service. But i want to get response value.
My code is shown below:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://www.w3schools.com/webservices/tempconvert.asmx', true);
// build SOAP request
var sr =
'<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>' +
'<CelsiusToFahrenheit xmlns="http://tempuri.org/">' +
'<Celsius>44</Celsius>' +
'</CelsiusToFahrenheit>'+
'</soapenv:Body>' +
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('done use firebug to see response');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
When i look in firebug, i realized web server response value is:
<?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><CelsiusToFahrenheitResponse xmlns="http://tempuri.org/"><CelsiusToFahrenheitResult>111.2</CelsiusToFahrenheitResult> </CelsiusToFahrenheitResponse></soap:Body></soap:Envelope>
But i dont know how can i get
111.2 value?
You are getting an xml response from your ajax call. Do do it correctly, you need to parse the xml code.
You can do easily it with jQuery:
var r = $(this.responseText).find("CelsiusToFahrenheitResult").text();