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?
Related
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 am trying to test a simple Ajax script using Javascript and I'm not receiving a response. The PHP script is placed in the htdocs folder of the local server and the HTML page that includes the Ajax calls is placed on my desktop. A readyState of 4 is received from the server but the status returned is 0, not 200.
The error generated on Firefox state:
NS_ERROR_DOM_BAD_URI: Access to restricted URI denied.
Here is the section of code responsible for calling the Ajax object:
var myRequest = getXMLHttpRequest();
function callAjax() {
var url = "localhost/clock.php";
var myRandom = parseInt(Math.random()*99999999);
myRequest. open("GET", url + "?rand=" + myRandom, true);
myRequest.onreadystatechange = responseAjax;
myRequest.send(null);
}
function responseAjax() {
if(myRequest.readyState == 4) {
if(myRequest.status == 200) {
var now = new Date();
var localTime = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
var serverTime = myRequest.responseText;
document.getElementById("clock").innerHTML = "Server: " + serverTime + "<br />Local: " + localTime;
} else {
alert("An error has occurred: " + myRequest.statusText);
}
}
}
Can anyone offer insight to my problem?
OSX 10.8.5
MAMP version 2.1.3
You say your file is on the desktop. You cannot open a local file ( file:// ) and do ajax. You need to access the file through your Apache server ( http:// ).
I have an MVC4 Web API application where i have my Api Controller and Code-First EF5 database and some JavaScript functions for the functionality of my app including my Ajax Calls for my Web Api Service.I did the project on MVC because i was having trouble installing Cordova in VS2012, so i have decided to use Eclipse/Android Phonegap platform.Is there a way where i can call my web api service and be able to retrieve my database data designed EF5(MVC4) in my Android Phonegap application without having to start from the beginning the same thing again.I know phonegap is basically Html(JavaScript and Css) but i am having trouble calling my service using the same HTML markup that i used MVC4.I am a beginner please let me know if what i am doing is possible and if not please do show me the light of how i can go about this. T*his is my Html code*
<script type="text/javascript" charset="utf-8" src="phonegap-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="barcodescanner.js"></script>
<script type="text/javascript" language="javascript" src="http://api.afrigis.co.za/loadjsapi/?key=...&version=2.6">
</script>
<script type="text/javascript" language="javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
//initialize watchID Variable
var watchID = null;
// device APIs are available
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 30000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
//declare a global map object
var agmap = null;
// declare zoom control of map
var zoomCtrl = null;
function initAGMap() {
agmap = new AGMap(document.getElementById("MapPanel"));
//TODO: must retrieve coords by device location not hard corded.
agmap.centreAndScale(new AGCoord(-25.7482681540537, 28.225935184269), 5); // zoom level 5 heres
// making zoom controls for map
var ctrlPos = new AGControlPosition(new AGPoint(10, 10), AGAnchor.TOP_LEFT);
zoomCtrl = new AGZoomControl(1);
agmap.addControl(zoomCtrl, ctrlPos);
}
function removeZoomCtrl()
{
zoomCtrl.remove();
}
//function search() {
// var lat = $('#latitude').val();
// var long = $('#longitude').val();
// $.ajax({
// url: "api/Attractions/?longitude=" + long + "&latitude=" + lat,
// type: "GET",
// success: function (data) {
// if (data == null) {
// $('#attractionName').html("No attractions to search");
// }
// else {
// $('#attractionName').html("You should visit " + data.Name);
// displayMap(data.Location.Geography.WellKnownText, data.Name);
// }
// }
// });
//}
//function GetCoordinate() {
//todo: get details from cordova, currently mocking up results
//return { latitude: -25.5, longitude: 28.5 };
}
function ShowCoordinate(coords) {
agmap.centreAndScale(new AGCoord(coords.latitude, coords.longitude), 5); // zoom level 5 here
var coord = new AGCoord(coords.latitude, coords.longitude);
var oMarker = new AGMarker(coord);
agmap.addOverlay(oMarker);
oMarker.show();
//todo: create a list of places found and display with marker on AfriGIS Map.
}
function ScanProduct()
{
//todo retrieve id from cordova as mockup
//This is mockup barcode
//return "1234";
//sample code using cordova barcodescanner plugin
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
//Callback function if barcodedont exist
function (error) {
alert("Scanning failed: " + error);
});
}
//Function to display Success or error in encoding.
function encode(type, data) {
window.plugins.barcodeScanner.encode(type, data, function(result) {
alert("encode success: " + result);
}, function(error) {
alert("encoding failed: " + error);
});}
function GetProductDetails(barcodeId,coords)
{
//Ajax Call to my web Api service
$.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
.done(function (data) {
$('#result').append(data.message)
console.log(data)
var list = $("#result").append('<ul></ul>').find('ul');
$.each(data.results, function (i, item)
{
if (data.results == null) {
$('#result').append(data.message)
}
else {
list.append('<li>ShopName :' + item.retailerName + '</li>');
list.append('<li>Name : ' + item.productName + '</li>');
list.append('<li>Rand :' + item.price + '</li>');
list.append('<li>Distance in Km :' + item.Distance + '</li>');
//Another Solution
//var ul = $("<ul></ul>")
//ul.append("<li> Rand" + data.results.productName + "</li>");
//ul.append("<li> Rand" + data.results.Retailer.Name + "</li>");
//ul.append("<li> Rand" + data.results.price + "</li>");
//ul.append("<li> Rand" + data.results.Distance + "</li>");
//$("#result").append(ul);
}
});
$("#result").append(ul);
});
}
function ShowProductDetails()
{
//todo: display product details
//return productdetails.barcodeId + productdetails.retailerName + ': R' + productdetails.Price + productdetails.Distance;
}
//loading javascript api
$(function () {
initAGMap();
var coord = GetCoordinate();
ShowCoordinate(coord);
var barcodeId = ScanProduct();
var productdetails = GetProductDetails(barcodeId, coord);
ShowProductDetails(productdetails);
});
</script>
It looks like you're on the right track. The obvious error right now is that it's using a relative URL (api/products/?barcodeId=) to call the Web API. Because the HTML is no longer hosted on the same server as the Web API (even though you might be running them both on your local machine still), this won't work anymore. You need to call the service with an absolute URL (for example, http://localhost:8888/api/products/?barcodeId=).
Where is your Web API hosted right now and how are you running the Cordova code? If the Web API is up and running on your local machine and your Cordova app is running on an emulator on the same machine, you should be able to call the service by supplying its full localhost path.
If it still doesn't work, you'll need to somehow debug the code and see what the errors are.
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.