Retrieve XML Data to use webpage - javascript

What I am trying to do:
Get location based off of IP (Done)
Use the City and Country code to use openweather's API (Done)
Read the XML into my webpage so that I can display the "Temperature" field.
This is my first venture into using XML in webpages, and I've tried for 3 days now with no success. I have searched google and stackoverflow, and have tried many things so far, including SimpleXMLElement, with no luck.
What I currently have on my page is just a generated link to the XML sheet for your location.
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
var city = geoip_city();
document.write('Link text');
</script>
How am I able to display the text from the required field on my page?
Thanks in advance! :)

It might be easier to change the API call to return JSON, in which case you could then use this code, the temps are stored in temp, temp_min and temp_max.
var country = geoip_country_code();
var city = geoip_city();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=json&units=metric', function( json ) {
var temp = json.main.temp;
var temp_min = json.main.temp_min;
var temp_max = json.main.temp_max;
document.write( 'Temp: ' + temp + '<br>');
document.write( 'Temp Min: ' + temp_min + '<br>');
document.write( 'Temp Max: ' + temp_max + '<br>');
});

You could use javascript library to convert the xml into a javascript object - one such library is called xml2json, it works as a jQuery plugin: http://www.fyneworks.com/jquery/xml-to-json/
Then you can simply do:
var xmlObject;
$.ajax({
url: url_of_xml,
success: function(data) {
xmlObject = $.xml2json(data);
}
});
Then you just need to place the data on your page. The object in my example is faked, but it gives you the idea:
// put this line in the success callback of your ajax call
// after you create the xmlObject
$('#temp').html(xmlObject.weather.temp);

To display the temperature you get the XML, and read one of the three temperature attributes from the XML returned:
$.get("http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=xml&units=metric", function(xml) {
avg = $(xml).find("temperature").attr("value"));
max = $(xml).find("temperature").attr("max"));
min = $(xml).find("temperature").attr("min"));
(using JQuery)

Related

YQL finance data with Java script not returning all queries each time

I am trying to incorporate financial data in my website (just a beginner)
I followed a youtube documentary that used some java script to to the query from a local machine not a server.
the script was supposed to return price daily changes to 4 different shares and display them.
It seemed to work at first, but now i see that it only returns some of the prices (or occasionally none) and when I refresh it may show a different change but never all 4 at the same time?
here is the HTML and Javascript
<script type="text/javascript">
var Base_URL = 'https://query.yahooapis.com/v1/public/yql?q=';
var yql_query = 'select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")';
var yql_query_str = encodeURI(Base_URL+yql_query);
var query_str_final = yql_query_str + '&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
$.getJSON(query_str_final, function(data){ console.log(data);
var changeValue = data.query.results.quote[0].Change;
console.log(changeValue);
document.getElementById("change").innerHTML = " Yahoo = " + changeValue; });
$.getJSON(query_str_final, function(data){ console.log(data);
var changeValue = data.query.results.quote[1].Change;
console.log(changeValue);
document.getElementById("change1").innerHTML = " Apple = " + changeValue; });
$.getJSON(query_str_final, function(data){ console.log(data);
var changeValue = data.query.results.quote[2].Change;
console.log(changeValue);
document.getElementById("change2").innerHTML = " Google = " + changeValue; });
$.getJSON(query_str_final, function(data){ console.log(data);
var changeValue = data.query.results.quote[3].Change;
console.log(changeValue);
document.getElementById("change3").innerHTML = " Microsoft = " + changeValue; });
</script>
any thoughts?
Try something like this where the changeValue ie 1,2,3 etc for each has a slightly different variable name plus the html change is done when the process is complete.
$.getJSON(query_str_final, function(data){ console.log(data);
changeValue1 = data.query.results.quote[1].Change;
console.log(changeValue);
}).done(function(){
document.getElementById("change1").innerHTML = " Apple = " +
changeValue1;});
Note: This makes the changValue1 variable global, which isn't the best but for testing.

Append image in function jquery

Good evening.
I have this jquery code which allows me, once you press the Enter key, to post a comment.
Fattio that I run an append with the username and the content that the user wants to publish.
In addition to the username I would also like to "hang" the profile picture using their path. How do I post a photo?
Thanks for your help. Here's the code:
function commento_post(id_post)
{
$('.form-commento'+id_post).click(function ()
{
$('#ins_commento'+id_post).keydown(function (e)
{
var message = $("#commento"+id_post).val();
var username = $("#username").val();
var id_user = $("#id_user").val();
if(e.keyCode === 13)
{
$.ajax(
{
type: 'POST',
url: 'http://localhost/laravel/public/index.php/post/ins_commento',
data: { commento: message, id_post: id_post },
success: function(data)
{
$('#commento'+id_post).val('');
$('#commentscontainer'+id_post).append
(
/*$(".username-commento"+id_post).html
(*/
$('<a/>',
{
text : username, href : 'http://localhost/laravel/public/index.php/utente/'+id_user
}).css({'font-weight':'bold'})
//)
).append(' ').append(message).append($('<br/>'));
var el = $('#numero_commenti'+id_post);
var num = parseInt(el.text());
el.text(num + 1);
}
});
}
});
});
}
In your success function, you could simplify everything quite a bit in the following way while not using jQuery append so much, but just using a variable to store your code and then appending it in one go. This will allow you to append all sort of elements, it's easily parseable for the you and it reduces the amount of calls you have to make.
// Add whatever you want your final HTML to look like to this variable
var html = "<a href='http://localhost/laravel/public/index.php/utente/" + id_user + "' style='font-weight: bold;'>" + username + "</a>";
html += message;
// add an image
html += "<img src='path/to/image.jpg' />"
html += "<br />";
// append to code you constructed above in one go
$('#commentscontainer' + id_post).append(html);
Update
I amended an incorrect quote and changed + id_user + "to + id_user + "', which makes everything after it work.

jQuery read XML URL

My below code working well but i need to import XML data from xml URL not from HTML file like this
if i need to retrieve image from XML how i can do that.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(document).ready(function(){
//$('#table').append('<h2>SHOWS</h2>');
$('#table').append('<table id="show_table">');
$(xml).find('show').each(function(){
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append(html);
});
//alert($('#show_table').html());
})
all what i need is change this var xml = "9/8 ... " to let the JQuery code read from the ONLINE URL
If you need to load XML data from the URL, you need to execute AJAX request, it may be something like this:
$(function() {
$.ajax({
type: "get",
url: "http://yoursite.com/yourfile.xml",
dataType: "xml",
success: function(data) {
/* handle data here */
$("#show_table").html(data);
},
error: function(xhr, status) {
/* handle error here */
$("#show_table").html(status);
}
});
});
Keep in mind, if you use AJAX you can place .xml file on the same domain name. In other case you need to set up cross-origin resource sharing (CORS).
EDITED:
I modified your code, now it appends td element to your table. But xml is still inside html.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(function() {
$(xml).find('show').each(function() {
console.log(this);
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append($(html));
});
});
But you need to modify your html file, check my solution here: http://jsfiddle.net/a4m73/
EDITED: full solution with loading xml from URL
I combined two parts described above, check here: http://jsfiddle.net/a4m73/1/
Use jquery-xpath, then you can easily do what you want like:
$(xml).xpath("//shows/show");
if you want know more about xpath just take a look on XML Path Language (XPath) document.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>";
$(document).ready(function () {
//$('#table').append('<h2>SHOWS</h2>');
$('#table').append('<table id="show_table">');
$(xml).xpath("//shows/show").each(function () {
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append(html);
});
})

Encoding a JSONP <script src = Request

I am attempting to access Google Books in order to an ISBN Code to get details of a book, I have a number of problem, which are:
A) I am trying to assemble a script request e.g. with the ISBN code concatenated into the URL. I have not managed to do this successfully - and I don't know why.
B) I then want to update a div in the DOM with this generated script dynamically, such that it will then execute.
C) I am finding it a bit of a puzzle as to the format of the returned data and the argument name of the function call contained in the Google response.
Has anyone else encountered the same problem and can offer guidance re A thru C above.
I enclose JavaScript code below.
$(document).ready(function() {
$('#viewbook-button').live('click', function() {
isbnCode = this.text;
alert("ISBN is : " + isbnCode + " " + this.text + " as well");
alert("Getting JSONP Google Books data");
isbnCode = "0451526538";
JSONPstr = '<' + 'script ' + 'src="' + 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode;
JSONPstr = JSONPstr + '&callback=handleJSONPResponse">' + '</script>';
alert("un-Escaped JSONP string" + JSONPstr);
escJSONPstr = escape( escJSONPstr );
alert("Escaped JSONP string");
//divstr = "";
//divstr = divstr + escape(<script src=");
//divstr = divstr + encodeURIComponent(https://www.googleapis.com/books/v1/volumes?q=ISBN);
//divstr = divstr + escape(isbnCode);
//divstr = divstr + encodeURIComponent(&callback=handleJSONPResponse);
//divstr = divstr + escape("></);
//divstr = divstr + escape(script);
//divstr = divstr + escape(>);
$('#jsonp-call').html(escJSONPstr);
// This will cause the handleJSONPResponse function to execute when the script is dynamically loadedinto div.
// The data wrapped in a function call will be returned from the Google Books server.
// This will cause the handleJSONPResponse function to execute below.
}); // end viewbook-button
}); // end document.ready
function handleJSONPResponse(response) {
var tmp = response;
alert(tmp);
};
</script>
</head>
<body>
<h2>Show Details of Books Ordered by a Customer</h2>
Get Customer Details
<br/><br/>
<div id="tablist">Tables will be Listed Here</div>
<br/><br/>
<div id="Google-call">The JSONP generated src= statement will go here and execute</div>
</body>
</html>
EDIT:
Problem solved - thanks everyone.
You're reinventing the wheel: jQuery has built-in JSONP support, so you don't need to faff about implementing it yourself. Use the $.ajax method:
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode,
dataType: 'jsonp',
success: function(response) {
console.log(response); // log the response object to the console
}
});
That should be all you need to do.

jquery, json and xml

I have a database at zoho creator. They feed me a json of the database content. I have trouble to parse and display that data with jquery or php or in html
Question : So how do I capture json data, and save (convert) it to file as XML. With the xml file I can parse it with jquery xpath easily... the "file" will be a local database, as a backup (if saved)
anybod have clue on that ?
as request.. here is the link for the query -link-
getting a way to display data from var i need is the minimum i must have !
like prod_categorie or prod_nom
note :
i can get help with any tutorial on
how to get xml data from zoho
any json to xml converter (jquery)
out there ?????
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div id="Liste_output"></div>
<script type="text/javascript">
jQuery.ajax({
url: "http://creatorexport.zoho.com/marcandremenard/application-lemieux/json/Liste_produits_View1/7GWhjVxYeNDePjPZnExCKy58Aqr21JX2hJEE6fAfgfkapEQnRjRd5RUy8wdjKuhmFEhJR9QRsBCUBjACAdSgmJNQSvxMt6geaMNC/",
dataType: "json",
success: function(data) {
var Liste_div = jQuery("#Liste_output");
var Liste_data = data["Liste_des_produits1"];
for (var i=0; i<Liste_data.length; ++i) {
var prod_i = Liste_data[i];
Liste_div.append('<div>' +
'<div>Nom: <span>' + prod_i["prod_nom"] + '</span></div>' +
'<img src="/images/prod/'+ prod_i["prod_photo"] +'"/>' +
'<div>Description: <span>' + prod_i["prod_desc"] + '</span></div>' +
'<div>Ingredient: <span>' + prod_i["prod_ingredient"] + '</span></div>' +
'<div>Odeur: <div class="odeur_cls"></div></div>' +
'<div>Certification: <div class="cert_cls"></div></div>' +
'</div>');
var odeur_data = prod_i["prod_odeur"];
for (var j=0; j<odeur_data.length; ++j) {
jQuery('#Liste_output odeur_cls').eq(j).append('<span>' +
odeur_data[j] + '</span>' + (j<odeur_data.length-1 ? ', ' : ''));
}
var cert_data = prod_i["prod_certification"];
for (var k=0; k<cert_data.length; ++k) {
jQuery('#Liste_output cert_cls').eq(k).append('<div>' + cert_data[k] + '</div>');
}
}
}
});
</script>
</body>
</html>
This will not work from a local file. The HTML must be served from the same domain as the database query, that is, it must be served from http://creatorexport.zoho.com (you can put it in the app subfolder)
– OR –
You must read the zoho docs and find out how to do a "callback" (sometimes called "JSONP"). Usually this is done by adding something like ?callback=data to the end of the URL.
Firstly, Javascript has no file-output capability. The best it can do is send data back to a server for processing there -- so the "capture json data, and save it to file as XML" idea is out.
What problems in particular are you having with using JSON? As it gets converted to a native Javascript object, I find it quite easy to work with myself. Though, I can see that if you wanted to use XPath to query it, JSON is no help. You should still be able to get to whatever data you need, but it might be a bit more verbose.
In your example JSON:
{"Liste_des_produits1":[{"Added_Time":"28-Sep-2009 16:35:03",
"prod_ingredient":"sgsdgds","prod_danger":["sans danger pour xyz"],"prod_odeur"..
You could access the prod_danger property like this:
$.getJSON(url, function(data) {
var danger = data.List_des_produits1[0].prod_danger;
});
If you are having trouble getting the right path to a property, Firebug is a great help with this. Just call this:
$.getJSON(url, function(data) {
console.log(data);
});
...and then you can browse through its properties in a tree-structure.
There are jQuery pluggins for such convertion, for example json2xml.

Categories