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");
});
Related
I want to put a text file into a javascript function and then somehow display that function in the html.
The javascript can't be inside the html file; it has to be referenced from outside the file like a:
Here is a picture of what I am trying to do (I don't have enough rep points):
https://i.ibb.co/xGxw1bm/1.png
I have tried:
I tried using "XMLHttpRequest" to try and display the text file in the front end html by uploading my text file to dropbox so I can be using the "https" method to communicated instead of "file://" since that doesn't work in the twitch developer rig
const Http = new XMLHttpRequest();
const url=' https://cors-anywhere.herokuapp.com/https://app.box.com/s/zkt7pbsv0cnnogafcxq8n5elmc9plxbz';
\\later in the code; because I didn't know where to put the rest of the http commands so I put them in the twitch.onAuthorized function which needs to be ran in this script anyway. I don't know what it does but it needs to be there and since its already a function I figured it would be better there. (Unless someone can make a function where all the https stuff is in one function.)
twitch.onAuthorized(function (auth) {
// save our credentials
token = auth.token;
tuid = auth.userId;
Http.open("GET", url);
Http.send();
Http.onreadystatechange=(e)=>{
console.log(Http.responseText);
setAuth(token);
$.ajax(requests.get)
}
});
I tried the document.getelement thingy but that doesn't ever explain to me how to put this in the html as text:
document.getElementById("demo").innerHTML
Everything I have seen on this has always said you can manipulate using a tag but I have not seen one example where this document.get thingy is in another javascript file and they have to reference it to the html. I always see it in the same file with the html.
What function can I use to extract that function into the html file without using a button? I just want it to display on like an object tag or an iframe tag.
I tried using the object tag....
It seems to work however......
I notice it pulls the website like an html file. Is there anyway to direct link a text file to the object tag but just the text data shows? Do I have to upload my text to a secure https? Can I even pull a text file from the web without it pulling in the html?
Here is the html file exact: (Note: This is testing, so none of the words matter in the html file. I am just trying to learn how to put text on here from another javascript file or backend.js javascript file. What tag or reference can I use to put a function from javascript into here without a button? Just on the screen I need the text.:
<!DOCTYPE html>
<html>
<head>
<title>Viewer Page</title>
</head>
<body style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">
<div id="app" class="full-height"></div>
<script src="twitch-ext.min.js"></script>
<script src="jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="viewer.js" type="text/javascript"></script>
<h2>Hello, World!</h2>
<p>Would you care to cycle a color?</p>
<object type="text/html" data="https://www.w3.org/TR/PNG/iso_8859-1.txt"></object>
</body>
</html>
Here is the viwer.js (this is where the javascript for getting the text file needs to be):
const Http = new XMLHttpRequest();
const url=' https://cors-anywhere.herokuapp.com/https://app.box.com/s/zkt7pbsv0cnnogafcxq8n5elmc9plxbz';
let token = '';
let tuid = '';
const twitch = window.Twitch.ext;
// create the request options for our Twitch API calls
const requests = {
set: createRequest('POST', 'output'),
};
function createRequest (type, method) {
return {
type: type,
url: location.protocol + '//localhost:8081/musicoutput/' + method,
success: updateBlock,
error: logError
};
}
function setAuth (token) {
Object.keys(requests).forEach((req) => {
twitch.rig.log('Setting auth headers');
requests[req].headers = { 'Authorization': 'Bearer ' + token };
});
}
twitch.onContext(function (context) {
twitch.rig.log(context);
});
twitch.onAuthorized(function (auth) {
// save our credentials
token = auth.token;
tuid = auth.userId;
Http.open("GET", url);
Http.send();
Http.onreadystatechange=(e)=>{
console.log(Http.responseText);
setAuth(token);
$.ajax(requests.get)
}
});
function updateBlock (hex) {
twitch.rig.log('Updating music info');
}
function logError(_, error, status) {
twitch.rig.log('EBS request returned '+status+' ('+error+')');
}
function logSuccess(hex, status) {
twitch.rig.log('EBS request returned '+hex+' ('+status+')');
}
In the console it's giving me the error "Uncaught SyntaxError: Unexpected token : ", but if I access direct SoundCloud URL in my browser then it's giving valid JSON. Earlier this code was working fine and today this issue started.
<html>
<head>
<script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script>
</head>
<body>
<h2>hellooo</h2>
</body>
</html>
Update:
Below is the actual code for which I am asking the question, above html I just created for example.
SoundCloud.prototype._jsonp = function (url, callback) {
var target = document.getElementsByTagName('script')[0] || document.head;
var script = document.createElement('script');
var id = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[id] = function (data) {
if (script.parentNode) {
script.parentNode.removeChild(script);
}
window[id] = function () {};
callback(data);
};
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + id;
target.parentNode.insertBefore(script, target);
};
I got the reason of issue, earlier soundcloud were responding response in jsonp but now they are providing JSON even I passed JsonP callback function. I had to make ajax request to fix it.
I used following code to fix it.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback( JSON.parse(this.responseText) );
}
};
xhttp.open("GET", url, true);
xhttp.send();
The following script tag expects JavaScript code in the source and not JSON.
<script src="file.js"></script>
I suppose that you want to use this externally produced json...
A way to "get" it is using an asynchronous ajax request like $.get(url,callback);
Calling it as a script will sure fail...
Because it's not a script.
Try to run the snippet!
var url = "https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"
var json;
$.get(url,function(result){
json = result;
// show in console
console.log(JSON.stringify(json));
// Now using it...
$("#json_usage").html(json.tag_list+" and all the "+json.permalink);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<!--script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script-->
</head>
<body>
<h2>hellooo <span id="json_usage"></span> !</h2>
</body>
</html>
In the above, the resulting json is placed in the json variable and then console logged.
Sorry you've been having trouble with JSONP responses from the SoundCloud API. This was due to a bug that made it into production in the last few days. We've just deployed a fix, and so this endpoint will now be returning valid JSONP responses rather than just JSON, if you specify a callback parameter. Sorry for the confusion!
I'm executing a web service call using JQuery and it's ajax function and I'm unable to parse the data coming back. When I alert the data (alert($(data).find("return").text()) its empty. I see the server responding with xml data as outlined below and when I alert(data) I get [object XMLDocument]. Is txt = $(data).find("return").text() valid given my XML structure with a namespace below? I can see the full xml string in firebug. Any ideas?
var txt = $(data).find("ns1\:return").text(); works on Chrome and Firefox, but not Safari
index.js:
$(function () {
$.ajax({
url: url,
success: function (data) {
var ndx = 0,
row,
**txt = $(data).find("return").text(),**
xml = unescape(txt),
xmlDoc = $.parseXML(xml),
firstrow = $(xmlDoc).find(
"results").children(":first");
// populate the table based on the results returned by
// the web service
$("table.results thead").empty();
$("table.results tbody").empty();
row = $("<tr/>");
row.append($("<th/>").text("#").addClass("ndx"));
firstrow.children().each(function () {
row.append($("<th/>").text(this.nodeName));
});
row.appendTo($("table.results thead"));
$(xmlDoc).find("row").each(function () {
row = $("<tr/>");
row.append($("<td/>").text(ndx + 1).addClass("ndx"));
$(this).children().each(function () {
row.append($("<td/>").text($(this).text()));
});
row.appendTo($("table.results tbody"));
ndx++;
});
// clear the table if no results were returned
if (ndx == 0) {
// no rows returned
$("table.results thead").empty();
$("table.results tbody").empty();
}
statusNotice("Records Returned: " + ndx);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// display the error returned by the web service
var xmlDoc = $(XMLHttpRequest.responseXML);
statusError(xmlDoc.find("Text").text());
},
complete: function(XMLHttpRequest, textStatus) {
// hide the busy dialog
$("#busy-dlg").dialog("close");
}
});
});
index.html:
Demo
<script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-min.js"></script>
<script type="text/javascript" src="js/jquery.layout-latest.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
//table displaying results from ajax call here
</body>
</html>
XML:
<ns1:executeResponse xmlns:ns1="http://sqlws.test.com">
<ns1:return>
<results>
<row>
<attribute1>value1</attribute1>
<attribute2>value2</attribute2>
</row>
<row>
<attribute1>value1</attribute1>
<attribute2>value2</attribute2>
</row>
</results>
</ns1:return>
</ns1:executeResponse>
When an element is prefixed by a namespace, you have to also add the namespace:
.find('ns1:return') does not work, because : is used by jQuery as pseudo-selectors.
.find('ns1\:return') does not work either, because a single backslash in a string is used as an escape character. "ns1\:return" becomes "ns1:return" which is equal to the previous one.
.find('ns1\\:return') should be used. The double backslash is used to escape the colon.
It appears that the last solution works fine in IE and Firefox, but not Opera, Chrome or Safari. To get maximum compatibility, use jQuery selectors with, and without fake prefix, ie. "ns1\\:return, return" instead of a plain ns1\\:return.
Demo: http://jsfiddle.net/5BQjv/51/
// For example, this is the result:
var data = '<ns1:executeResponse xmlns:ns1="http://sqlws.test.com">' +
'<ns1:return>' +
'<results> <row> ... </row> </results>' +
'</ns1:return>' +
'</ns1:executeResponse>';
// The very first thing is to parse the string as XML. NOT later!
var $xmlDoc = $($.parseXML(data));
// Then, look for the element with the namespace:
var $txt = $xmlDoc.find('ns1\\:return, return');
// No need to use unescape or something, just use DOM manipulation:
// `results` is the immediate child. Don't use .find, but .children
var $firstrow = $txt.children("results").children(":first");
As you may have noticed, I have prefixed some variables with a dollar sign. It's the convention to prefix variables which refer to jQuery objects with a dollar sign, to avoid confusion during/after development.
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.
I need to create a javascript function that will write a page based on the url, so basically I am trying to create a javascript function that will check the url, and find the corresponding xml item from there.
The reason behind this is so that the html page can just be duplicated, renamed, and the xml updated, and the page will fill in everything else from the xml sheet.
please let me know whether this is the completely incorrect way to do it, of it there is a better way. thanks!!!
XML CODE::
<!--XML INFORMATION-->
<channel>
<design>
<motion><!--design content-->
<item><!--//////////POST//////////POST//////////POST//////////-->
<tag>/portfolio_dec.html</tag>
<!--RSS INFORMATION-->
<title>Decoze</title>
<link>http://payamrajabi.com/portfoliotest.html</link>
<description><img src="http://payamrajabi.com/thumbs/small_jump.png" title="JUMP!." /></description>
<!--PROJECT CONTENT-->
<project><!--project start-->
<titl>TITLE</titl><!--project title-->
<dsc>PROJECT DESCRIPTION</dsc><!--project description-->
</project><!--project end-->
</item><!--//////////END//////////END//////////END//////////-->
</motion>
</design>
</channel>
JAVASCRIPT:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "code/content9.xml",
dataType: "xml",
success: function(xml) {
var xpathname = window.location.pathname;
var xproject = $(xml).find('tag').text();
if (xpathname == xproject) {
$(xml).find('item').children('tag').text(xpathname).each(function(){
var ttl = $(this).find('titl').text();
$('<p>'+ttl+'</p>').appendTo('h1#ttl');
});
$(xml).find('item').children('tag').text(xpathname).each(function(){
var dsc = $(this).find('dsc').text();
$('<p>'+dsc+'</p>').appendTo('h1#ttl');
});
} else {
PUT ERROR MESSAGE HERE
}
}
});
});
and THE HTML:
<html>
<head>
<script type="text/javascript" src="code/jquery-1.3.1.js"></script>
<script type="text/javascript" src="code/project/project_design.js"></script>
</head>
<body>
<h1 id="ttl"></h1>
<p id="dsc"></p>
</body>
</html>
any help would really be appreciated, i am frairly new to javascript/jquery/xml, and am really having trouble with this. The primary thing I want to do is have an xml file that populates a site, with each item being the content for a new page, in this case of a portfolio item.
cheers!
willem
Hmm... I'm afraid you don't quite understand how jquery works.
Your code should look something like this:
var xpathname = window.location.pathname;
var xitem = $(xml).find('tag:contains(' + xpathname + ')').parent();
if (xproject.length != 0) {
$('#ttl').append('<p>' + xitem.find('titl').text() + '</p>');
$('#dsc').append('<p>' + xitem.find('dsc').text() + '</p>');
}
else {
$('#err').text('The page you requested does not exist');
}
Demo 1
Here's a quick demo. Take a look at the source to see the XML and the JavaScript.
http://jsbin.com/ujiho#itemOne
http://jsbin.com/ujiho#itemTwo
http://jsbin.com/ujiho#itemThree
Demo 2
I've created another demo that uses $.get to retrieve the XML from a separate URL.
http://jsbin.com/aqefo#nov
http://jsbin.com/aqefo#dec
The XML: http://jsbin.com/afiwa
Here's the JavaScript. Let me know if you need help understanding anything.
$(function(){
$.get(
'http://jsbin.com/afiwa',
function(xml){
var hash = window.location.hash.substring(1);
if ($.trim(hash) === '') {
showError();
return;
}
var xitem = $(xml).find('urlname:contains(' + hash + ')').parent();
if (xitem.length != 0) {
$('#ttl').append(xitem.find('titl').text());
$('#dsc').append( xitem.find('dsc').text());
}
else {
showError();
}
function showError() {
$('#err').text('The page you requested does not exist');
}
}
);
});