jquery, json and xml - javascript

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.

Related

Getting a new JSON object when clicking a button (jQuery)

I'm brand new to webdev, I'm trying to build a web app that gets a new quote whenever the button #getQuote is clicked.
This is my my js code:
$(document).ready(function() {
// function get_new will get a new JSON object
function get_new() {
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content.slice(3, -6);
var author = '- ' + a[0].title;
var my_quote = $('<i class="fa fa-quote-left"></i> ' + quote + ' <i class="fa fa-quote-right"></i>');
$('.quoteBody').html(my_quote);
$('.quoteAuthor').html(author);
// tweet the quote
$("#tweet").click(function() {
$(this).attr('href', 'https://twitter.com/intent/tweet?text=' + '"' + quote + '" - ' + author).attr("target", "_blank");
});
});
}
// calling function to appear as default
get_new();
// when clicked, get new quote
$('#getQuote').click(function() {
get_new();
});
});
Any help would be appreciated guys.
Here's the codepen for anyone interested:
https://codepen.io/tadm123/pen/YNvdyr
As others have pointed, it's just a cache issue on codepen.
Add this line to your code to set cache false:
$.ajaxSetup({ cache: false });
Be careful using this in a live environment, you dont want to affect all your ajax requests with cache:false. So I'd recommend you using a normal jQuery ajax call and set the property cache to false specifically to this function only:
$.ajax({
cache: false,
url: "/path/to/file.json",
dataType: "json",
success: function(data) {
...
}
});
Your code is 100% right. It just so happens that the browser is caching the result of the url you're accessing. I noticed that Codepen was caching the result and my browser was caching it too when I tested it with files on my computer. So after it hits that URL the first time, it thinks something along the lines of "Oh, I've already gone to this URL and I already know what the result is. So to save time, I'll just give it the same data as before."
To combat this (this might be considered hacky?), add the current time to the end of the URL (because the time will always be different) like so:
function get_new(){
var currentDate = new Date().getTime(); // create new date
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&date=" + currentDate, function(a) { // add it to end of URL
var quote = a[0].content.slice(3,-6);
var author = '- ' + a[0].title;
var my_quote = $('<i class="fa fa-quote-left"></i> ' + quote + ' <i class="fa fa-quote-right"></i>');
$('.quoteBody').html(my_quote);
$('.quoteAuthor').html(author);
// tweet the quote
$("#tweet").click(function(){
$(this).attr('href', 'https://twitter.com/intent/tweet?text='+ '"'+ quote + '" - ' + author).attr("target","_blank");
});
});
}
Also sometimes the result will come slowly, but I think that's because of the speed of the server your requesting the quotes from. Another challenge can be to have a loader show while it's getting a quote from the server.
Put cache false in your URL. This is because you are getting same data again and again
https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&cache=false&callback
Close... to get it to work with the console closed, the $.ajaxSetup({ cache: false }); didn't work. However, randomizing the URL did:
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=&cache="+Math.random(), function(a) {

How to reed rss feeds with jquery mobile

I tried to read an RSS feed from an external website with the following code:
$.get('http://myrssurl.com',function (XMLmediaArray) {
$(XMLmediaArray).find('item').each(function() {
var item = $(this);
var title = item.find('title').text();
var description = item.find('description').text();
var link = item.find('link').text();
var image = item.find('enclosure[type="image/jpeg"]').attr('url');
});
});
I got an error message which says:
XMLHttpRequest cannot load http://myrssurl.com. No '*Access-Control-Allow-Origin*' header is present on the requested resource. Origin 'localhost is therefore not allowed access.
Do you know how to solve this?
Thanks for your help! in the meanwhile I tried to use the GOOGLE RSS FEED service but I also have to deal with a problem by using this:
in the html file I'm using this:
<script type="text/javascript">
new rssdisplayer("msndiv","http://www.myrssfeedurl",6,"date, description");
</script>
and in the Javascript file the follow:
google.load("feeds", "1"); //Load Google Ajax Feed API (version 1)
function rssdisplayer(divid, url, feedlimit, showoptions){
this.showoptions=showoptions || "" //get string of options to show ("date" and/or "description"wink
var feedpointer=new google.feeds.Feed(url) //create new instance of Google Ajax Feed API
feedpointer.setNumEntries(feedlimit) //set number of items to display
document.write('<div id="'+divid+'">Loading feed, </div>')
this.feedcontainer=document.getElementById(divid)
var displayer=this
feedpointer.load(function(r){displayer.formatoutput(r)}) //call Feed.load() to retrieve and output RSS feed
}
rssdisplayer.prototype.formatdate=function(datestr){
var itemdate=new Date(datestr)
return "<span style='color:gray; font-size: 90%'>"+itemdate.toLocaleString()+"</span>"
}
rssdisplayer.prototype.formatoutput=function(result){
if (!result.error){ //if RSS feed successfully fetched
var thefeeds=result.feed.entries //get all feed entries as a JSON array
var rssoutput="<ul>"
for (var i=0; i<thefeeds.length; i++){ //loop through entries
var itemtitle="" + thefeeds[i].title + ""
var itemdate=/date/i.test(this.showoptions)? this.formatdate(thefeeds[i].publishedDate) : ""
var itemdescription=/description/i.test(this.showoptions)? "<br />"+thefeeds[i].content : ""
rssoutput+="<li>" + itemtitle + " " + itemdate + itemdescription + "</li>"
}
rssoutput+="</ul>"
this.feedcontainer.innerHTML=rssoutput
}
else //else, output error
alert("Error fetching feeds: "+result.error.message)
}
but when I execute it in the Browser I get this error message:
Uncaught ReferenceError: rssdisplayer is not defined (index):127 (anonymous function)
Do you guys know what the issue is?
This is an AJAX security: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
You are not allowed to query on other websites.
I would recommend to parse the RSS feed on your server and re-format it in JSON for convenience.
I solved it with the Google API RSS Feed Service. The error came because the rssdisplayer.js file was included too late in the html file. Include it directly after the jquery mobile javascript

Retrieve XML Data to use webpage

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)

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.

what is wrong with this JSON parsing using YQL?

i want to parse remote JSON file using JQuery, YQL(you know cross domain proble, so yql is best)
but i dont know what is misssing in this code ?
index.html
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
<style type="text/css">
body { text-align: center; }
</style>
</head>
<body onLoad="gova();">
<div id="container">
</div>
<table id="userdata" border="1">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody></tbody>
</table>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="cross-domain-requests.js"></script>
<script type="text/javascript">
function gova() {
var path = $('http://mapleleafrealities.com/jsondata.php').val();
requestCrossDomain('http://mapleleafrealities.com/jsondata.php', function(results) {
$('#container').html(results);
});
return false;
}
</script>
</body>
</html>
cross-domain-requests.js
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// If no url was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
i want to display unformatted data in to table ? how ?
plese give solution where is the probleam or what is missing ?
thanks in advance !! :)
i want to parse remote JSON file using JQuery, YQL
You say that you want to parse some JSON, but your YQL query asks for HTML and the YQL URL asks for an XML response!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
If you really want to work with JSON, change that line to something like below. It a) uses the json table (since that is the nature of the content on the site) and b) tells YQL to return JSON because you're using the jQuery.getJSON() function!
var yql = 'http://query.yahooapis.com/v1/public/yql?'
+ 'q=' + encodeURIComponent('select * from json where url=#url')
+ '&url=' + encodeURIComponent(site)
+ '&format=json&callback=?';
Now that YQL returns JSON, you can get at the json object via data.query.results.json which then contains an array of userdata objects. See a fuller example, based on your code, which takes the JSON response from YQL and populates the table rows using jQuery.template()
http://jsbin.com/umuri5/edit
Two thins:
1)The json being returned in not well formed. For some reason the userdata element is prefixed with "\n , hence making the element userdata unavailable,
2)You should be using data.results[0].userdata to iterate over each user. i.e:
$.each(data.results[0].userdata, function(i,user){
var tblRow =
"<tr>"
+"<td>"+user.first+"</td>"
+"<td>"+user.last+"</td>"
+"<td>"+user.email+"</td>"
+"<td>"+user.city+"</td>"
+"</tr>"
$(tblRow).appendTo("#userdata tbody");
});

Categories