Parsing xml data from a remote website - javascript

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());

Related

load json data into js

I am learning how to load json data into .js file. I have created a employee.json file. I saved my js and json file and on the desktop. What I trying to do is to put all the id in json files into an array in the js. I do not know what could be wrong. Hope someone could help me out. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON with jQuery</title>
</head>
<body>
<p id="demo"></p>
<h1><h2>
<script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
}
});
document.getElementById("demo").innerHTML = res.toString();
</script>
</body>
</html>
{
"person": [
{
"id" : 1,
"firstName" : "Lokesh"
},
{
"id" : 2,
"firstName" : "bryant"
}
{
"id" : 3,
"firstName" : "kobe"
}
]
}
Error 1: Typing error. <script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>. You mistyped the src of the script, accidentally adding another another <script> start tag.
Error 2: Misplaced statement. document.getElementById("demo").innerHTML = res.toString(); should be placed in the success callback function, so it will be executed only after the server responds. If it executes prematurely, res will still be [].
Error 3: type: 'GET' should be method: 'GET', according to the docs (though 'GET' is default so you don't need to explicitly write this).
Use this:
<p id="demo"></p>
<h1><h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
You can't use the local json to read. it gives cross origin request failure. so deploy both the files (html and json) into a we server and execute. or place the json data onto some web url(http://somesite/myjson) and then request that url and see.
First of all, the JSON shouldn't be existed as in physical "file". It has to be generated by a backend language / web service etc. The JSON tags inside a manually created "file" have high chance of data invalidity upon parsing.
Solution
Use a Web Service to generate valid JSON output. And from Javascript end, use:
JSON.stringify( data );

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.

using javascript onload() and ajax to retrieve php array

I'm using onload() and ajax to get the array from php, but it didnt work. The html page should be able to get the array from n1.php and alert("GOOD"), but it's not giving any response, not even alerting GOOD or BAD so i really dont know what's wrong with the code. How can I fix this??
n1.html:
<!DOCTYPE html>
<html>
<body onload="getArr();">
here
</body>
<script type="text/javascript">
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
}
</script></html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
The request must contains the type of request. Also the dataType refers on data you are going to send,as long as you don't send any data, it does not need here.
Try this:
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Try this
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = json_data; // Do not parse json_data because dataType is 'json'
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Now, two things to note here:
You have not passed HTTP Method in the ajax but by default it is GET as mentioned here in jQuery AJAX docs. Please pass appropriate method type if it is not GET.
Since you have sent dataType as 'json', you need not parse json received in the response in success handler.

How to redirect response from ajax request

I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
Not using ajax would make this easier:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.
If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
Please try this.
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Your response is an object containing the full HTML for a page in the responseText property.
You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.
...
complete : function(response) {
$(body).html(response.responseText);
}
But i suggest you don't and there could be style and other conflicts with whats already there on the page.
In your HTML add a div with id as 'content', something like this
<div id='content'/>
Since your response is html in your complete function append the content into the div like this -
complete : function(response) {
$('#content').append(response.responseText);
}
Let me know if you still face issues.
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});

$.ajax not working properly on IE6

Basically, I have something like this:
$.ajax({
type: "GET",
url: "my_url",
cache: true,
success: function(data) {
/* code here */
},
dataType: 'json'
});
This code is working in all tested browsers (IE7/8, chrome, safari, firefox) but in IE6 the success function is not called.
I used Fiddler to see what's going on in the HTTP requests, and everything seems normal, I get the expected result as an HTTP answer but success doesn't seem to be called in IE6, same for onerror.
Any thoughts?
Try using complete instead of success. If it fires consistently then you can evaluate the status code to determine if it was successful...
$.ajax({
type: "GET",
cache: true,
complete: function(xhr) {
if(xhr.status != 200) {
throw "Error!";
return;
}
var data = xhr.responseText;
}
});
Are you sure it's not just a cache thing? Remove your browsers cache and test again.
A good test case would be getting rid of the 'cache' option, and also making it a POST request (since GET ajax calls are always cached in ie6).
You don't mention the server-side code you're using. I had some issues with jQuery AJAX calls in IE when using ASP.NET on the server side (a ashx handler). They went away when I read the request fully before starting to write the response (even though in my case I was using POST, not GET request, so the body of the request contained some data).
I wrote the following simple ASP.NET project to test your issue in IE6. However I'm unable to reproduce (IE6 SP2 running in virtual machine hitting IIS 7.5 shows the alert box from success handler properly). Could you try running it in your environment and reporting whether it works from IE6 for you?
Note: Sometimes when I cleared IE6 cache and commented out the "SetCacheability" line in ashx.cs, the first click on "Send" button would not show the success alert box, although subsequent clicks did show it. Maybe all you need is adding "no-cache" headers to the call response in your implementation?
file index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX GET test</title>
</head>
<body>
<input type="button" id="test" value="Send" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$("#test").click(function () {
$.ajax({
url: "Api.ashx?param=one",
cache: true,
type: "GET",
dataType: "json",
success: function (data) {
alert("Success, result = " + data.result);
},
error: function (request, status, err) {
alert("Error");
}
});
});
</script>
</body>
</html>
file Api.ashx
<%# WebHandler Language="C#" CodeBehind="Api.ashx.cs" Class="AjaxTest.Api" %>
file Api.ashx.cs
using System.Diagnostics;
using System.Text;
using System.Web;
namespace AjaxTest
{
public class Api : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
var param = context.Request["param"]; // this flushes the request
Trace.WriteLine("Request: \"" + context.Request.RawUrl + "\", param: \"" + param + "\"", "** Debug");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Write("{\"result\":\"" + param + "\"}");
}
}
}
What happens if you add a failure function, and alert out the responseText within there?
$.ajax({
type: "GET",
url: "my_url",
cache: true,
success: function(data) {
/* code here */
},
error: function(data) {
alert(data.responseText);
},
dataType: 'json'});
http://docs.jquery.com/Ajax/jQuery.ajax#options

Categories