XML Parsing remote server - javascript

I have followed some tutorials on how to parse XML from remote websites and came across the wonderfully articulated question and answer in stackoverflow.
However even after following the question, following program is not working.
<!DOCTYPE html>
<html>
<head>
<title>Aviation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText) ;
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
The website which I am trying to parse is same.
US FAA
Also I want to develop it as stand alone application i.e. Just HTML interacting with the remote website.

As mentioned, you can (need to) use jsonp because faa.gov apparently forgot to add the appropriate header to their API responses.
By the way - always prefer json over xml with Javascript - it's so much nicer to work with.
// ask faa.gov to add the HTTP header "Access-Control-Allow-Origin: *" to their response
// then you can use this
// jQuery.getJSON('http://services.faa.gov/airport/status/IAD?format=json');
jQuery.ajax({
url: 'http://services.faa.gov/airport/status/IAD?format=json',
dataType: 'jsonp',
success: function (data) {
document.myform.result1.value = data.city;
}
});

Related

Uncaught ReferenceError: CallApi is not defined

I'm trying to call an API using a submit button but i'm getting the following errors when i inspect the page on Chrome:
Uncaught ReferenceError: CallApi is not defined
My code is as follows:
<script type="text/javascript" href="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
function CallApi(event)
{
var username = "****"
var password = "***"
var engagamentId=$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val();
if (engagamentId)
$.ajax({
url: 'https://hello.com/engagements/engagementdetails/'+ $('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(),
type: "GET",
crossDomain: true,
dataType: "jsonp",
jsonp: "json_callback",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)"
},
success: function (data) {
$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(data.EngagementID);
$('#ctl00_ctl05_fvlc_Form1_txtClientName').val(data.ClientName);
$('#ctl00_ctl05_fvlc_Form1_txtPOA').val(data.AccountingEndPeriod);
$('#ctl00_ctl05_fvlc_Form1_txtCurrentTaxYear').val(data.TaxYear);
$('#ctl00_ctl05_fvlc_Form1_txtEngagementManager').val(data.EngagementManager);
},
error:function(a,b,c)
{
alert(a.responseText);
//alert("Engagement not found!");
}
});
else alert("Please enter 'Engagement ID'");
}
And my button has the following HTML:
<input type="button" value="Get Engagement Details" onclick="CallApi(event)" class="RadButton RadButton_Cora rbButton rbRounded rbIconButton">
Could anyone advise what i'm doing wrong? I have looked at related questions/answers but can't seem to get it working.
Thanks!
the function is not defined, so most likely the javascript file is not included correctly.to prevent mistakes like this:
include files using src instead of href
<script src="myscripts.js"></script>
include files in the correct order (first jquery, then your script)
understand what the term hoisting means in js
check developer tools in chrome (network) to check if files are loaded correctly or check window.CallApi, since it should be defined globally
if you define scripts direclty in html, still wrap them with script tags <script>function CallApi(event) {console.log(event);};</script>
You are both trying to import JQuery and write a custom JS code in the same script tag.
You must include JQuery in a tag.
Then in another tag declare your custom JS code.
Do it this way (i'm just doing an alert for demonstration purpose) :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function CallApi(event) {
alert('test')
}
</script>
</head>
<body>
<input type="button" value="Get Engagement Details" onclick="CallApi(event)" />
</body>
</html>
The following HTML file works for me, in so far as it can call your API url, and get a 404, then alert in the error callback:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function CallApi(event)
{
var username = "****"
var password = "***"
var engagamentId=$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val();
if (engagamentId)
$.ajax({
url: 'https://hello.com/engagements/engagementdetails/'+
$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(),
type: "GET",
crossDomain: true,
dataType: "jsonp",
jsonp: "json_callback",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
success: function (data) {
$('#ctl00_ctl05_fvlc_Form1_txtEngagementID').val(data.EngagementID);
$('#ctl00_ctl05_fvlc_Form1_txtClientName').val(data.ClientName);
$('#ctl00_ctl05_fvlc_Form1_txtPOA').val(data.AccountingEndPeriod);
$('#ctl00_ctl05_fvlc_Form1_txtCurrentTaxYear').val(data.TaxYear);
$('#ctl00_ctl05_fvlc_Form1_txtEngagementManager').val(data.EngagementManager);
},
error:function(a,b,c)
{
alert(a.responseText);
//alert("Engagement not found!");
}
});
else alert("Please enter 'Engagement ID'");
}
</script>
<input type="button" value="Get Engagement Details" onclick="CallApi(event)"
class="RadButton RadButton_Cora rbButton rbRounded rbIconButton">
<input type="text" id="ctl00_ctl05_fvlc_Form1_txtEngagementID" value="foo" />
</html>
It doesn't work because on moment the DOM is created by the browser, the CallApi function doesn't exist yet. This occurs because of the order that element and the scripts is loaded. I believe if you insert the script in <head> section, the function should work.
I recommend change to something like this:
$ (document) .ready (function () {
$ ('#id-of-my-button-element').on('click', CallApi);
});

how to print data sent by ajax post method in javascript

I need to post data and display it also. I am using ajax post method. I am able to get the event Id where data is saved, but not able to display the data. I searched a lot and got some answer also. I tried it in my code, but didn't got the result. My code is:
<!DOCTYPE html>
<html>
<head>
<title>POST API</title>
<script type="text/javascript" src="http://ajax.googleapis.com /ajax/libs /jquery/1.2.6/jquery.js"></script>
</head>
<body>
<button id="btn1">Check HTTP POST</button>
<p>Display sample output from POST API:</p>
<p id="one" />wEventId :
<p id="two" />
<script>
$(document).ready(function() {
$("#btn1").click(function() {
$.ajax({
url: 'url',
dataType: 'json',
type: 'POST',
crossDomain: true,
contentType: 'application/json',
data: {},
success: function(data) {
console.log(data);
document.getElementById("two").innerHTML = data.result.wEventId;
},
failure: function(errMsg) {
console.log(errMsg);
}
var myData = data;
myData = new Array;
});
});
});
</script>
</body>
</html>
Anyone please help me how to modify the code to print the data saved. I have not given the url as it is an internal server and supposed not to disclose it. Thanks in advance.
First I need to know, what is the structure of your json data.
Assuming that it is in a format like given below:
{"field_A":"value_a","field_b":"value_b"}
your code where you are trying to print as innerHTML should be like this:
success: function(data)
{
console.log(data);
document.getElementById("two").innerHTML = data.field_A;
},
Try to adjust accordingly.
I am still surprised from where are you getting the result of data.result.wEventId

Want to fetch the RSS feed and render on the html using jquery

I am trying to render this url http://online.wsj.com/xml/rss/3_7085.xml to fetch all the xml information using jquery but i came across something on jsonp thats giving me a callback ,how do i handle that callback to render each node in the html.
I tried the below code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>RSS Feed testing</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var result;
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://online.wsj.com/xml/rss/3_7085.xml",
dataType: "jsonp",
success: function (result) {
$("div").html(result);
},
});
}
$(document).ready(function(e) {
jsonparser1();
});
</script>
</script>
</head>
<body>
<div></div>
</body>
</html>
I googled, about jsonp ,its quite confusing to me.
Rss feed in xml format. Use datatype = json.
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://online.wsj.com/xml/rss/3_7085.xml",
dataType: "xml",
success: function (result) {
$("div").html(result);
},
});
}
This is not doable directly. You need to use a service like Superfeedr's Feed API or Google's.
These services will serve your the content of the feed in JSON using JSONP so that you can easily integrate any feed into any page.

How to get plain xml from file

I search for a method to get plain xml(with tags ect.) from a file and save it so the localStorage.
I found a few opportunities, but every one of them returns the xml without tags. I prefer jQuery to do this...
I tried $.get, $("").load() and AJAX but I don't get it. I just want to save the whole xml as string into the localStorage and read it out later (and work with it).
Does anyone have a idea?
Regards
You can use:
$.ajax({
url: 'http://example.com',
dataType: 'text',
success: function (data) {
localStorage.setItem('xml-content', data);
}
});
This will provide you the XML document as plain text and save it to the localStorage.
Here is a full solution:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<pre id="output">
</pre>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function setXML() {
$.ajax({
url: 'test.xml',
dataType: 'text',
success: function (data) {
localStorage.setItem('xml-content', data);
getXML();
}
});
}
function getXML() {
var xml = localStorage.getItem('xml-content');
$('#output').text(xml);
}
setXML();
</script>
</body>
</html>

Parsing xml data from a remote website

I would like to parse the xml data from a remote website http://services.faa.gov/airport/status/IAD?format=xml...But I was not able to parse the xml data and I am only getting error. But I was able to parse the JSON data from the same remote website http://services.faa.gov/airport/status/IAD?format=json. The code I have used to parse the xml data is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Aviation</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = xml.city;
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
I was only getting the error as 'o Error' in the alert box since I have printed the error message. Anybody please helpout to parse the xml data from the remote website.
Note: I have also 'City' instead of 'city' but its not working...
Thanks in advance...
I don't believe that will work since the service is still returning xml. jsonp is expecting a n object literal as an argument to pass to the callback. I believe if you run this locally you'll realize there's no data being consumable in your success. Try this
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=json",
dataType: "jsonp",
success: function (data) {
document.myform.result1.value = data.city;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Here is the example for creating a proxy with asp.net mvc 3. I just created an action that returns a ContentResult which maps to a string but I define the content type as text/xml. This simply just makes a webrequest to the service and reads the stream in to a string to send back in the response.
[HttpGet]
public ContentResult XmlExample()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.faa.gov/airport/status/IAD?format=xml");
string xml = null;
using (WebResponse response = request.GetResponse())
{
using (var xmlStream = new StreamReader(response.GetResponseStream()))
{
xml = xmlStream.ReadToEnd();
}
}
return Content(xml, "text/xml");
}
Your xmlParser function will look like this:
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "XmlExample",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
jQuery ajax's converts the data by using $.parseXML internally which removes the requirement for us to even call this in the success block. At that point you have a jQuery object that you can use it's default DOM functions to find the City Node.
Make sure to replace the XmlExample with the url that it maps to based on your controller.
The solution is quite simple (mentioned in Pekka's comment)
1.On your server add a file IAD_proxy.php
2.Put the following code inside it
header("Content-type: text/xml; charset=utf-8");
echo file_get_contents('http://services.faa.gov/airport/status/IAD?format=xml');
3.Change the url in your Ajax request to IAD_proxy.php.
In case you're using any other server-side language, try to implement the same idea.
Edit: Please read about Parsing XML With jQuery, here's what I've tried and it's working.
Javscript:
$.ajax({
type: "GET",
url: "IAD_proxy.php",
dataType: "xml",
success: function (xml) {
alert($(xml).find('City').text());
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
Here I tried it with document.write($(xml).find('City').text());

Categories