I'm starting off with js.
I want to fetch data from a server with xml. I wonder how to send a request as, and get an anser in xml through javascript functions.
It says I need a POST-Request and send an xml in the form:
<?xml version="1.0" encoding="UTF-8"?>
<ft>
<request clientId="123" apiName="api_search_location_stops_nearby" apiVersion="2.0">
<client clientId="123"/>
<requestType>api_search_location_stops_nearby</requestType>
<outputCoords>WGS84</outputCoords>
<fromCoordName>WGS84</fromCoordName>
<fromType>coords</fromType>
<fromWgs84Lat>48.22</fromWgs84Lat>
<fromWgs84Lon>16.39</fromWgs84Lon>
</request>
</ft>
To then get an xml answer. It has 2 or 3 nodes in it, which I'm interested in. From there on, it'll be no big deal.
It is all about a strange API from the vienna public transport company:
http://akirk.github.io/Wiener-Linien-API/
I basically want to get (open)data from them.
Here:
https://techscreen.tuwien.ac.at/node/794
I found a solution for php..
My try:
// Bare bones XML writer - no attributes
function xmlElement(name,content){
var xml
if (!content){
xml = '<' + name + '>' + '</' + name + '>'
}
else {
xml = '<'+ name + '>' + content + '</' + name + '>'
}
return xml
}
function sendRequest()
{
var xmlReq
xmlReq = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
xmlReq = xmlReq + "<ft>";
xmlReq = xmlReq + "<request clientId=\"123\" apiName=\"api_get_monitor\" apiVersion=\"2.0\">";
xmlReq = xmlReq + "<client clientId=\"123\"/>";
xmlReq = xmlReq + xmlElement("requestType", "api_get_monitor");
xmlReq = xmlReq + xmlElement("monitor",
xmlElement("outputCoords", "WGS84") +
xmlElement("type","stop") +
xmlElement("name","60201040") +
xmlElement("year","2013") +
xmlElement("month","10") +
xmlElement("day","3") +
xmlElement("hour","8") +
xmlElement("minute","0") +
xmlElement("line") +
xmlElement("sourceFrom","stoplist") );
xmlReq = xmlReq + "</request>" + "</ft>";
text1.text = xmlReq;
var xhr = new XMLHttpRequest();
xhr.onload = handleRequest;
xhr.open("POST", "http://webservice.qando.at/2.0/webservice.ft"); // POST or GET
xhr.send(xmlReq);
// xhr.responseXML // this is allways null
}
function handleRequest(answer)
{
console.log(answer.responseType);
console.log(answer.responseXML);
}
The core points of my question: On my code, should there be GET or POST? Is the request built up to fit the style above (or do I need linebreaks or convert to a DOM xml thing)? How does the recieving thing work. Am I doing this right? Should the variable answer then contain the xml with the answer?
This code is somehow not working. I printed the xml-string to the console and it looks just like above (without linebreaks). But the handleRequest function doesn't print anything (it is not called at all).
Thanks in advance!
Looks like it was good allready.
I got the wrong clientID. That was basically it. Then there was just a small modification to make:
xhr.onreadystatechange = function(){ page.handleRequest(xhr); }
..to send the xmlHttpRequest over to the function. This worked for me.
Related
I'm trying to create an ASPX page on my SharePoint site to read existing InfoPath forms. Testing locally with JavaScript and XMLHttpRequest worked fine but when the page is uploaded to SharePoint something very odd happens if the XML file has a specific line of data in it. When testing with simple XML files this line causes a problem:
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.4"?>
When present in the XML file I'm trying to read, something odd happens. Instead of getting the contents of the file I get what appears to be an HTML page from SharePoint. The page doesn't display anything and has references to InfoPath and SharePoint libraries. I have no idea where the HTML is coming from. Removing that single line from the XML file causes everything to work as expected. Running outside of SharePoint appears to work as well. I will include a sample XML file and code I used to test.
Update : If the input file extension is TXT and not XML then the problem goes away. I assume this means that SharePoint is running code when XML files are read and injecting itself into my get request.
<?xml version="1.0" encoding="utf-8"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.4"?>
<my:myFields xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2017-05-05T14:19:13">
<my:User_Name>Joe</my:User_Name>
<my:Email_Address>joe.smith#abc.com</my:Email_Address>
</my:myFields>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="lib/jquery/jquery-3.4.1.min.js"></script>
<title></title>
<script>
var oReq = new XMLHttpRequest();
oReq.addEventListener("progress", updateProgress);
oReq.addEventListener("error", transferFailed);
oReq.addEventListener("abort", transferCanceled);
oReq.addEventListener("loadend", transferComplete);
function Test_Req_xml() {
console.log("starting test_req_xml function");
let filename = document.getElementById('inFileName').value;
console.log("file name " + filename);
oReq.addEventListener("load", transferComplete_xml);
oReq.open("GET", filename);
oReq.responseType = "document";
oReq.send();
}
var transferComplete_xml = function (response) {
console.log({ 'transferComplete xml response:': response });
console.log({ 'oReq.responseXML': oReq.responseXML });
console.log({ 'oReq.responseType': oReq.responseType });
console.log({ 'oReq.responseURL': oReq.responseURL });
console.log({ 'oReq': oReq });
parseFile(oReq.responseXML.documentElement.outerHTML);
};
// progress on transfers from the server to the client (downloads)
function updateProgress(oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total * 100;
console.log("percent " + percentComplete);
} else {
// Unable to compute progress information since the total size is unknown
console.log("loaded is " + oEvent.loaded);
}
}
function transferComplete(evt) {
console.log("The transfer is complete.");
}
function transferFailed(evt) {
console.log("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
console.log("The transfer has been canceled by the user.");
}
//this will parse XML file and output it to website
var parseFile = function (text) {
var xmlDoc = $.parseXML(text),
$xml = $(xmlDoc),
$email = $xml.find("Email_Address"),
$naming = $xml.find("User_Name");
console.log({ 'xmldoc ': xmlDoc });
var currentdate = new Date();
var datetime = currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/" + currentdate.getFullYear() + " # " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
$("#output").empty();
$("#output").append("<br/>");
$("#output").append("<span>Date: " + datetime + "</span><br/>");
$("#output").append("<span>Name: " + $naming.text() + "</span><br/>");
$("#output").append("<span>Email: " + $email.text() + "</span><br/>");
};
</script>
</head>
<body>
<div class="row m-sm">
<span>File name: </span><input id="inFileName" type="text" class="form-control" placeholder="" value="test_xml_file3.xml">
</div>
<div class="row m-sm">
<button id="btnTest3" class="btn btn-outline-secondary" type="button" onclick="Test_Req_xml()">Test xml </button>
</div>
<div class="row m-sm">
<ul id="output"></ul>
</div>
</body>
</html>
I am not entirely sure how it happens but my guess is SharePoint Online is intercepting the get request for files with the XML extension and when it finds the line below it attempts to run some code against the request. I don't see any issues when the file doesn't have an XML extension, nor do I see an issue when the line below is missing from an XML file. Now I need to find out if there is a way around this.
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.4"?>
I want to import a WSDL in XML file to my JavaScript project, which will allow my to use web client to search info.
Is there any special way to import it into my project, or do I need a package, or need to convert it into JS? I know there is a soap package in NPM, but I hope it's not the only way to do that. I've also read tutorials on W3 and still not quite sure how to manage that.
I've got something like this:
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', '127.0.0.1/start.html', true);
// build SOAP request
var sr =
'<soapenv:Envelope ' +
'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" ' +
'xmlns:aut="http://demo.krd.pl/Authorization" xmlns:dto="http://demo.krd.pl/Chase3.1/Dto"> ' +
'<soapenv:Header> ' +
'<aut:Authorization> '+
'<aut:AuthorizationType>LoginAndPassword</aut:AuthorizationType> ' +
'<aut:Login>login</aut:Login> ' +
'<aut:Password>password</aut:Password> ' +
'</aut:Authorization> ' +
'</soapenv:Header> ' +
'<soapenv:Body> ' +
'<dto:SearchNonConsumerRequest> ' +
'<dto:Number>24041803749</dto:Number> ' +
'<dto:NumberType>TaxId</dto:NumberType> ' +
'</dto:SearchNonConsumerRequest> ' +
'</soapenv:Body> ' +
'</soapenv:Envelope> ';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('done. use firebug/console to see network response');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// ...
}
Also, where the response will be saved or will it just be posted in console?
I'm using Javascript to call a SOAP webservice. Using firebug, I can see that the request is successful, and I see the XML SOAP response.
How can I display the response on the webpage? Or even better - how can I display a single node within the XML SOAP response? I thought maybe I can use XPath - but it doesn't seem to be working.
Here is my code:
<html>
<head>
<title>SOAP Client Test</title>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://mysoapurl.com', true);
// build 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);
// send request
// ...
// This XPath query should get us the <GetResponse> element from the SOAP XML Response
var query = "//ns1:GetResponse[1]";
// This object defines the namespaces used in the query
var namespaceMapping = {
ns1: "http://tempuri.org/", // SOAP namespace
diffgr: "urn:schemas-microsoft-com" // the 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>
Any help is greatly appreciated. Thanks for looking.
You can use the evaluate method on the responseXML:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://mysoapurl.com', true);
// build 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.onload = function(evt) {
var doc = this.responseXML;
var namespaceMapping = {
ns1: "http://tempuri.org/",
diffgr: "urn:schemas-microsoft-com"
};
var node = doc.evaluate('//ns1:GetResponse[1]', doc,
function (prefix) {
return namespaceMapping[prefix];
},
XPathResult.FIRST_ORDERED_NODE_TYPE,
null).singleNodeValue;
if (node != null) {
// now access node.textContent respectively run further queries on node
}
};
xmlhttp.send(sr);
I have to send the japanese name trough XMLHttpRequest. but it displays encoding problem... my tpl page is in utf-8 charset.
here is my code.
function getFormData(dno,rno) {
var name = document.getElementById("f_nickname").value;
var digNo = dno;
var resNo = rno;
var strVal = digNo + "-" + resNo;
stp.push(strVal);
var xhr = new XMLHttpRequest();
if (!xhr) return false;
var url = 'ajax.php' + '?prc=' + 'diagnoses' + '&name=' + name + '&diagres=' + stp;
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(stp);
return true;
}
i have passing url like this:
http://crp.com/ajax.php?prc=diagnoses&name=大阪&diagres=0-0,1-3,2-2,3-3,4-3,5-2
but it displays in Ajax.php like
http://crp.com/ajax.php?prc=diagnoses&name=ƒsƒU&diagres=0-0,1-3,2-2,3-3,4-3,5-2
tried in many ways... How to solve?
thanks in advance...
Use encodeURIComponent for such parameters in url.
var url = 'ajax.php' + '?prc=' + 'diagnoses' + '&name=' + encodeURIComponent(name) + '&diagres=' + stp;
It will result in url like:
http://crp.com/ajax.php?prc=diagnoses&name=%E5%A4%A7%E9%98%AA&diagres=0-0,1-3,2-2,3-3,4-3,5-2
And webserver will handle it properly.
Try adding:
xmlHttp.setRequestHeader('Content-type', 'text/xml;charset=utf-8');
Use:
encodeURIComponent(name) instead of just name
I wrote a Flickr search engine that makes a call to either a public feed or a FlickrApi depending on a selected drop down box.
examples of the JSONP function calls that are returned:
a) jsonFlickrApi({"photos":{"page":1, "pages":201, "perpage":100, "total":"20042", "photo":[{"id":"5101738723"...
b) jsonFlickrFeed({ "title": "Recent Uploads tagged red","link": "http://www.flickr.com/photos/tags/red/","description": "", ....
the strange thing is that in my local install (xampp) both work fine and i get images back BUT when i host the exact same code on the above domain then the jsonFlickrApi doesn't work. What i notice (by looking at Firebug) is that for the jsonFlickrApi the response Header says Connection close
Also, Firebug doesn't show me a Response tab when i submit a request to the jsonFlickrApi
here is the code:
function makeCall(uri)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", "jsonget.php?url="+uri, true);
xmlhttp.send();
}
function jsonFlickrApi(response)
{
var data= response.photos.photo ;
var output = "";
output += "<img src=http://farm" + data[4].farm + ".static.flickr.com/" + data[1].server + "/" + data[4].id + "_" + data[4].secret + ".jpg>";
document.getElementById("cell-0").innerHTML = output ;
}
//Public Feed
function jsonFlickrFeed(response)
{
var data= response.items[0].media.m ;
alert(data);
var output = "";
output += "<img src=" + data+ ">";
document.getElementById("cell-0").innerHTML = output ;
}
function callback()
{
//console.log("Ready State: " + xmlhttp.readyState + "\nStatus" + xmlhttp.status);
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var jsonResponse = xmlhttp.responseText;
jsonResponse = eval(jsonResponse);
}
}
examples of calls:
a)
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json×tamp=1339189838017
b)
http://api.flickr.com/services/feeds/photos_public.gne?tags=red&format=json×tamp=1339190039407
Question: why does my connection close? why is it working on localhost and not on the actual domain?
Looking at the HTTP response headers of
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json×tamp=1339189838017
I get a 302 with location
http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json×tamp=1339189838017
So, what flicker wants to tell you is "use www.flicker.com instead of flicker.com!". With this URL I get content.