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);
Related
I have the following xml document
<?xml version="1.0" ?>
<result searchKeyword="Mathematics">
<video>
<title>Chaos Game</title>
<channel>Numberphile</channel>
<view>428K</view>
<link>http://www.youtube.com/watch?v=kbKtFN71Lfs</link>
<image>http://i.ytimg.com/vi/kbKtFN71Lfs/0.jpg</image>
<length>8:38</length>
</video>
<video>
<title>Australian Story: Meet Eddie Woo, the maths teacher you wish you'd had in high school</title>
<channel>ABC News (Australia)</channel>
<view>223K</view>
<link>http://www.youtube.com/watch?v=SjIHB8WzJek</link>
<image>http://i.ytimg.com/vi/SjIHB8WzJek/0.jpg</image>
<length>28:08</length>
</video>
<video>
<title>Ham Sandwich Problem</title>
<channel>Numberphile</channel>
<view>557K</view>
<link>http://www.youtube.com/watch?v=YCXmUi56rao</link>
<image>http://i.ytimg.com/vi/YCXmUi56rao/0.jpg</image>
<length>5:53</length>
</video>
<video>
<title>Magic Square Party Trick</title>
<channel>Numberphile</channel>
<view>312K</view>
<link>http://www.youtube.com/watch?v=aQxCnmhqZko</link>
<image>http://i.ytimg.com/vi/aQxCnmhqZko/0.jpg</image>
<length>3:57</length>
</video>
<video>
<title>The 8 Queen Problem</title>
<channel>Numberphile</channel>
<view>909K</view>
<link>http://www.youtube.com/watch?v=jPcBU0Z2Hj8</link>
<image>http://i.ytimg.com/vi/jPcBU0Z2Hj8/0.jpg</image>
<length>7:03</length>
</video>
</result>
I have created this html file which has an AJAX call to get the xml file but it return all the values as "undefined"
<html>
<head>
<title>A7-Question2</title>
<script>
function getSearch()
{
// create an XMLHttpRequest
var xhttp = new XMLHttpRequest();
//create a handler for the readyState change
xhttp.onreadystatechange = function() {
readyStateChangeHandler(xhttp);
};
//get XML file by making async call
xhttp.open("GET", "A7.xml", true);
xhttp.send();
}
// handler for the readyState change
function readyStateChangeHandler(xhttp){
if (xhttp.readyState == 4){
// readyState = 4 means DONE
if(xhttp.status == 200){
// status = 200 means OK
handleStatusSuccess(xhttp);
}else{
// status is NOT OK
handleStatusFailure(xhttp);
}
}
}
// XMLHttpRequest failed
function handleStatusFailure(xhttp){
// display error message
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
// XMLHttpRequest success
function handleStatusSuccess(xhttp){
var xml = xhttp.responseXML;
// print XML on the console
console.log(xml);
// parse the XML into an object
var searchResult = parseXML(xml);
// print object on the console
console.log(searchResult);
// display the object on the page
display(searchResult);
}
// parse the XML into an object
function parseXML(xml){
var resultElement = xml.getElementsByTagName("result")[0];
//create a receipt object to hold the information in the xml file
var searchResult = {};
searchResult.searchKeyword= resultElement.getAttribute("searchKeyword");
var videoElements = xml.getElementsByTagName("video");
//create an array to hold the items
searchResult.videoArray = [];
for(var i=0; i< videoElements.length; i++){
var video = {};
video.title = videoElements[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
video.channel = Number(videoElements[i].getElementsByTagName("channel")[0].childNodes[0].nodeValue);
video.view = Number(videoElements[i].getElementsByTagName("view")[0].childNodes[0].nodeValue);
video.link = Number(videoElements[i].getElementsByTagName("link")[0].childNodes[0].nodeValue);
video.image = Number(videoElements[i].getElementsByTagName("image")[0].childNodes[0].nodeValue);
searchResult.videoArray.push(video);
};
return searchResult;
}
// display the searcg result object on the page
function display(searchResult){
var html = "<p>searchKeyword: Mathematics</p>";
for(var i=0; i<searchResult.videoArray.length; i++){
var video = searchResult.videoArray[i];
html += "title: " + searchResult.title + "<br/>";
html += "channel: " + searchResult.channel + "<br/>";
html += "view: " + searchResult.view + "<br/>";
html += "link: " + searchResult.link + "<br/>";
html += "image: " + searchResult.image + "<br/>";
html += "length: " + searchResult.length + "<br/>";
}
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = html;
}
</script>
</head>
<body>
<button onclick="getSearch()">Get Search Result</button>
<div id="display"></div>
</body>
</html>
Is the problem with my success function? Is it returning null because it hasn't returned all the values or something due to how AJAX runs?
Thanks heaps for any help
There's a lot of code to go over and a working snippet can't be produced because we can't put the XML file here.
This answer is making an assumption that your response from the XMLHttpRequest is null and the problem does not lie in any of your parsing functions.
It also seems that you're over complicating the request process by passing it around to many functions when it's quite simple itself.
Here is an example I made locally that correctly logged the XML to the console:
<!doctype html>
<html>
<head>
<title>A7-Questions2</title>
</head>
<body>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xml = xhttp.responseXML;
// Logs just fine for me. You can do your parsing here.
console.log(xml);
}
};
xhttp.onerror = function() {
// Display error message.
var displayDiv = document.getElementById('display');
displayDiv.textContent = 'XMLHttpRequest failed status: ' + xhttp.status;
};
xhttp.open('GET', './path/to/xml.xml');
xhttp.send();
</script>
</body>
</html>
I have some issues retrieving info from python and try to show the data in a html page
I get the date from a python script (data.py)
import cx_Oracle
import json
lst_proveedores=[{}]
conn_str = 'user/pass#database'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute('select id, name from provider')
for row in c:
record1 = {"id":row[0], "name":row[1]}
lst_proveedores.append(record1)
json_string = json.dumps(lst_proveedores)
print json_string
conn.close()
I try to parse the info with AJAX in a html page
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function ajax_get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("GET", "prov1.py", true);
hr.responseType = "JSON";
hr.setRequestHeader("Content-Type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
results.innerHTML = "";
for(var obj in data){
results.innerHTML += data[obj].id+" is "+data[obj].nombre+"<hr />";
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>
but doesn't work
I setup apache to execute python scripts and work with very simple scripts, but doesn't work when I retrieve data from the database
How can I show the data in a html page?
Or what language or framework may I can use to show the data
Any advice
I am desperate
Thanks in advance
First of all, you should try visit your python files in browser. If you can't see json print on page, there're problems in your server or python code.
If it works, that may be something wrong in your Ajax request.
You can use jQuery or zepto.js to help. They contain a method of Ajax: $.ajax.
You can visit: http://zeptojs.com
And search "$.ajax" on the page for help; )
===============================================================
try this:
//var data = JSON.parse(hr.responseText);
var data = JSON.parse(hr.response);
===============================================================
and this is my onreadystatechange function code, use it if it helps:
ajaxObject.onreadystatechange = function(){
//console.info('[Ajax request process] url:' + url +'; readyState:' + ajaxObject.readyState + '; status:' + ajaxObject.status);
if (ajaxObject.readyState == 4 && ((ajaxObject.status >= 200 && ajaxObject.status < 300) || ajaxObject.status == 304)){
var result = null;
switch (dataType){
case 'text':
result = ajaxObject.responseText;
break;
case 'xml':
result = ajaxObject.responseXML;
break;
case 'json':
default:
result = ajaxObject.response ? JSON.parse(ajaxObject.response) : null;
break;
}
if (typeof(success) == 'function'){
success(result,url);
}
}else if (ajaxObject.readyState > 1 && !((ajaxObject.status >= 200 && ajaxObject.status < 300) || ajaxObject.status == 304)){
console.warn('[Ajax request fail] url:' + url +'; readyState:' + ajaxObject.readyState + '; status:' + ajaxObject.status);
if (typeof(error) === 'function' && errorCallbackCount == 0){error(url);errorCallbackCount++;}
return false;
}
}
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.
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.
Basically, I want to have an interactive button on my website, that, when clicked, sends some data to the server in order to be checked and display the response (without form sending / page reload).
I thought it would be something like:
function checkData()
{
var req = new XMLHttpRequest();
var conf = document.getElementById('my_text_area').value;
req.open("GET", 'check_data', true);
req.onreadystatechange = function ()
{
var pre = document.getElementById('check_data_out');
pre.innerHTML = req.responseText;
}
req.send(conf);
return false;
}
And on the server side:
#get('/check_data')
def check_data():
# Process the content and answer something...
content = str(request.is_ajax) + ' - ' + str(request.GET) + ' - ' + str(request.POST)
return content
But this obviously doesn't work. Either it is not the right way to send data via javascript or not the right way to access it in bottle.py.
Showing me how it works is highly appreciated.
You can use dojo for client side logic.
var button = dojo.byId('button_id'); // button_id refers to the id of the button you want to click
dojo.connect(button,'onclick',dojo.xhrGet({
url: '/check_data',
handleAs : 'text',
load : function(response){
dojo.byId('button_id').innerHTML = response;
}
}));