I am attempting to parse a JSON object located on another page on my website. The page is a hosted ecommerce platform, so I don't have server side access or control over certain elements on page.
I have some code that i'm using that is returning a strange error. I've tested this snippet (with a different URL of course) on another site running the same platform and it does it fact work.
website: http://www.falcontechjax.com
$.get('no-risk-diagnostic-2.aspx', function(data) {
var prodImgDetail = $.parseJSON($(data).find("#imginfo").html());
console.log(prodImgDetail);
});
On that page, there is a div container with the id "imginfo, that contains a JSON object.
<div id="imginfo" style="display:none;">{gallery : [{thumbnail : '/images/products/thumb/pipe.jpg', display : '/images/products/display/pipe.jpg', detailed : '/images/products/detail/pipe.jpg', alt : '', title : '' },{thumbnail : '/images/products/thumb/logo_printres1.jpg', display : '/images/products/display/logo_printres1.jpg', detailed : '/images/products/detail/logo_printres1.jpg', alt : 'PC Computer Diagnostic & Repair in Jacksonville FL', title : '' }],active : {thumbnail : '/images/products/thumb/pipe.jpg', display : '/images/products/display/pipe.jpg', detailed : '/images/products/detail/pipe.jpg', alt : '', title : '' }}</div>
The error I get when I run it is:
Uncaught SyntaxError: Unexpected token g jquery-1.7.2.min.js
update
Just to advise everyone, there is a version of this setup which works on another site on the same platform as mine:
Site: www.allvintagegames.com
$.get( "nes-adventures-of-bayou-billy.aspx", function( data ) {
var imgThumb, imgDisplay, imgDetailed, imgAlt, imgTitle;
var mycrap = $.parseJSON($(data).find("#imginfo").html());
//img information
$.each(mycrap.gallery, function(i, object) {
//alert(object);
imgThumb = object.thumbnail;
imgDisplay = object.display;
imgDetailed = object.detailed;
imgAlt = object.alt;
imgTitle = object.title;
});
//product information
var prodinf = $.parseJSON($(data).find("#iteminfo").html());
var infoLowprice = prodinf.lowprice;
var infoId = prodinf.id;
var infoName = prodinf.name;
var infoCaption = prodinf.caption;
var infoPrice = prodinf.price;
var infoSaleprice = prodinf.saleprice;
var infoCode = prodinf.code;
var infoOrderable = prodinf.orderable;
$("body").append("<img src='"+imgThumb+"' />");
$("body").append("<img src='"+imgDisplay+"' />");
$("body").append("<img src='"+imgDetailed+"' />");
$("body").append("<br />");
$("body").append(infoLowprice + "<br/>");
$("body").append(infoId + "<br/>");
$("body").append(infoName + "<br/>");
$("body").append(infoCaption + "<br/>");
$("body").append(infoPrice + "<br/>");
$("body").append(infoSaleprice + "<br/>");
$("body").append(infoCode + "<br/>");
$("body").append(infoOrderable + "<br/>");
});
This last example includes another object (#iteminfo contents) which is reference on the applicable page, just under the #imginfo div.
Any help figuring this out would be most appreciated!
As Felix King says, the JSON text is not properly formatted. You can see it if you try this in your debug console:
JSON.parse('{gallery: "foo"}')
and then this:
JSON.parse('{"gallery": "foo"}')
You'll see that when the key names are unquoted it doesn't work, which is what your JSON string has. One option is to instead use eval() to parse the string. Using eval is a terrible idea generally though, as it puts the code in your page at the mercy of whatever the server returns, which could be malicious code.
Related
Attempting to create a script that will pull information from an API requested XML document and put it into a 2D array.
Upon making the Get request
https://api.example.com/v1.svc/users?apikey=MY-KEY&source=MY-APP&limit=1000
An XML is produced for each user looking like
<User>
<Id>Rdh9Rsi3k4U1</Id>
<UserName>firstlast#email.com</UserName>
<FirstName>First</FirstName>
<LastName>Last</LastName>
<Active>true</Active>
<Email>firstlast#email.com</Email>
<AccessLevel>Learner</AccessLevel>
</User>
Each user has a similar looking output stacked on top of each other. How could this be scrubbed into an array? Example, the first array would have 7 "columns" with all shown information with each user having a row.
b
So I figured it out for anyone looking for an answer to this type of question in the future. Basically, I found out that the API I was trying to reach (not actually "citrowske.com" as shown in the example) did not allow for CORS or jsonp which left me with the only option of using a Proxy.
Shown is an example of code similar to what I ended up using (below), along with the test XML file shown here
A basic explanation of how this works, it uses the proxy to get the XML file and stores it as "xml" found as "function(xml)". Then the XML doc is searched and each section that starts with "User" gets the "FirstName" and "LastName" data pulled from it and appended to dropdown in the HTML section named "yourdropdownbox".
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://citrowske.com/xml.xml',
function (xml) {
//console.log("> ", xml);
//$("#viewer").html(xml);
////////////////////////////////////
var select = $('#yourdropdownbox');
select.append('<option value="">Select a User</option>');
$(xml).find('User').each(function(){
var FirstNames = $(this).find('FirstName').text();
var LastNames = $(this).find('LastName').text();
select.append("<option value='"+ FirstNames +"'>"+FirstNames+" "+LastNames+"</option>");
});
}
////////////////////////////////////
);
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select id="yourdropdownbox">
</select>
As a note, Proxy's are not known for being extremely secure, so watch out what you use this for.
Also, if I wanted to turn the data into an array instead of appending it each time I could have added
var firstnamesarray = ["0"];
var lastnamesarry = ["0"];
var i = 0;
Above the top row of forward-slashes and then replaced:
var FirstNames = $(this).find('FirstName').text();
var LastNames = $(this).find('LastName').text();
with
firstnamesarry[i] = $(this).find('FirstName').text();
lastnamesarry[i] = $(this).find('LastName').text();
i = i+1;
and replaced the "select.append" First & Last Names with
firstnamearry[i] & lastnamearry[i]
To view a working example, check out the jsfiddle here
I have this jzebra applet that I need to do some client side ticket printing.
This is the applets html definition:
<applet id="jzebra" name="jzebra" code="jzebra.PrintApplet.class" archive="../../../../../../web/org.openbravo.howtos/lib/jzebra.jar"
width="10px" height="10px">
The function I call in the form button is this:
function printDocument() {
var applet = document.jzebra;
var frm = document.frmMain;
var url = frm.elements["inpftpOBDir"].value;
var file ="0.txt";
var archivo = url + "/" + file;
if (applet != null) {
var printname = frm.elements["inpPrinterName"].value;
var indice = frm.inpPrinterSelected.selectedIndex;
var printselected = frm.inpPrinterSelected.options[indice].text;
alert(printname);
alert(printselected);
if(printselected == ""){
// printname = "zebra"
//alert('Default : ' + printname);
applet.findPrinter(printname);
monitorFinding();
} else {
//alert('Selected : ' + printselected);
applet.findPrinter(printname);
monitorFinding();
}
alert('File : ' + archivo);
// applet.findPrinter(printname);
applet.appendFile(archivo);
// Send characters/raw commands to printer
applet.print();
alert('The document was sent to the printer.');
}
}
I checked the console and there is a definition of applet, but when it reaches applet.findPrinter(printname), just explodes because applet.findPrinter is not a function.
Has anyone faced this struggle before? I have seen that there is a little gray square in the top left corner of my page. When I hover on it, it displays "undefined".
I finally came up with a very complex solution, having to use jnlp. I will post my code later for references, if anyone else find similar problems.
I have written a function to display some paragraph tags from an external webpage. For some reason the results are displayed in firebug console but not showing on the web page as I wanted (blank page).
function requestCrossDomain(callback){
var querylink = "select * from html where url='http://somedomain.com'" +
" and xpath='/html/body/div/div/div[2]/div/div/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
if (typeof callback === 'function'){
callback(data);
}
});
}
My firebug console shows the below value.
{"query":{"count":1,"created":"2013-12-23T06:31:46Z","lang":"en-US","results":{"dd":{"p":"Hills: High"}}}}
How can I modify the code to display the value of the P tag, which is "Hills: High"
I'm calling the function from HTML code and trying to display the value inside "#targetWrapper"
requestCrossDomain(function(results){
$('#targetWrapper').html(results);
});
Edited to reflect a functional fiddle
$(document).ready(function(){
requestCrossDomain();
});
function requestCrossDomain(){
var querylink = "select * from html where url='http://www.bom.gov.au/wa/forecasts" +
"/armadale.shtml' and xpath='/html/body/div/div/div[2]/div/div" +
"/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
$('#targetWrapper').html(data.query.results.dl.dd[0].p);
$("#targetWrapper").append("<br/><strong>" + JSON.stringify(data) + "</strong>");
});
}
Your data format was very much off the mark AND you cannot have two functions with the same name.
The object you get back from $.getJSON is a simple Javascript Object. You can access it just as you would any other object:
In this case, you'd use:
requestCrossDomain(function(results) {
$("#targetWrapper").html(results.query.results.dd.p);
}
I would highly recommend that you read the MDN documentation I linked above. Having MDN bookmarked is also a good idea; it's a great resource to have easy access to.
I am trying to generate a table of data from a JSON file using Javascript but am having difficulty because of the bean:write tag. The bean: is getting removed, so only <write name="offenderCountVO" property="addressCount"/> seems to be getting parsed. Is this approach even feasible?
From the page that generates the table:
// Build profile section from JSON file
$.getJSON('<%=request.getContextPath()%>/jsp/json/offenderProfileJSON.jsp', function(data) {
//alert('loading JSON');
var items = [];
var table = $('<table class="profile"><\/table>');
var profileCols = 2;
var td = "";
// Build array of profile categories
for (i = 0; i < data.length; i++) {
//alert("building items");
// Check if this category can be displayed in this module
var item = data[i];
var modules = item["modules"];
//alert("Start check");
if (modules.indexOf(appName) > 0) {
// This category should be displayed
//alert ("Passed");
var label = item["label"];
var link = item["link"];
var name = item["name"];
var property = item["property"];
newCategory = { label: label, modules: modules, link: link, name: name, property: property };
items.push(newCategory);
}
}
// Alphabetically sort categories by label
//alert(items.length);
for (i = 0; i < items.length; i++) {
html = '<tr><td><a href="<%=request.getContextPath()%>/' + items[i].link + '">'
+ items[i].label + '</a></td><td>\u003Cbean\u003Awrite name="'
+ items[i].name + '" property="' + items[i].property + '" /\u003E</td></tr>';
}
$("#testArea").html(html);
//table.appendTo("#testArea");
alert("Done");
}).error(function() {
$("#testArea").html('<span class="error">Error parsing JSON.</span>');
});
The JSON file:
[
{
"label" : "Address",
"modules" : "AGNT,BOOKING,DIO,OMP,OTA",
"link" : "offenderAddress.do?method=list",
"name" : "offenderCountVO",
"property" : "addressCount"
},
{
"label" : "Assessments",
"modules" : "AGNT,BOPP,OMP,OTA",
"link" : "offenderAssessmentList.do?method=list",
"name" : "offenderCountVO",
"property" : "assessmentCount"
}
]
I hope I've explained the issue well enough -- I'm working on several different projects and my head is spinning right now, so let me know if you need any clarification. Any guidance would be appreciated.
<bean:write> is a tag understood by JSP on the server-side, at the point when the initial page is created.
Using:
'<td>\u003Cbean\u003Awrite name="'+ items[i].name + '" property="' + items[i].property + '" /\u003E</td>'
from JavaScript makes no sense because the web browser that includes the resultant <bean:write> tag in its page DOM doesn't know anything about Java or bean tags. When the browser's HTML parser sees <bean:write> it thinks only "that's some write tag that I don't know about, spelled funny" and not "I had better ask the server-side what it's value for the property of that bean is".
If you want the browser to see the server-side value of a variable, you must return that value itself in the JSON response to the browser, not just a name and value pair that only mean anything to the bean-based server side.
Note also that dropping unescaped strings into HTML markup is dangerous. Without HTML-escaping, you have cross-site-scripting security holes when any of the item values may contain user-submitted values. Use DOM-property methods to set element text and attribute values instead of trying to create HTML markup strings from JavaScript. eg:
<input type="hidden" id="contextPath" value="<c:out value="${pageContext.request.contextPath}"/>"/>
...
var cp = document.getElementById('contextPath').value;
for (var i= 0; i<items.length; i++) {
table.append(
$('<tr>').append(
$('<td>').append(
$('<a>', {href: cp+'/'+items[i].link, text: items[i].label})
)
).append(
$('<td>', {text: items[i].value_of_whichever_property_it_is})
)
);
}
If I write code in the JavaScript console of Chrome, I can retrieve the whole HTML source code by entering:
var a = document.body.InnerHTML; alert(a);
For fb_dtsg on Facebook, I can easily extract it by writing:
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
Now, I am trying to extract the code "h=AfJSxEzzdTSrz-pS" from the Facebook Page. The h value is especially useful for Facebook reporting.
How can I get the h value for reporting? I don't know what the h value is; the h value is totally different when you communicate with different users. Without that h correct value, you can not report. Actually, the h value is AfXXXXXXXXXXX (11 character values after 'Af'), that is what I know.
Do you have any ideas for getting the value or any function to generate on Facebook page.
The Facebook Source snippet is below, you can view source on facebook profile, and search h=Af, you will get the value:
<code class="hidden_elem" id="ukftg4w44">
<!-- <div class="mtm mlm">
...
....
<span class="itemLabel fsm">Unfriend...</span></a></li>
<li class="uiMenuItem" data-label="Report/Block...">
<a class="itemAnchor" role="menuitem" tabindex="-1" href="/ajax/report/social.php?content_type=0&cid=1352686914&rid=1352686914&ref=http%3A%2F%2Fwww.facebook.com%2 F%3Fq&h=AfjSxEzzdTSrz-pS&from_gear=timeline" rel="dialog">
<span class="itemLabel fsm">Report/Block...</span></a></li></ul></div>
...
....
</div> -->
</code>
Please guide me. How can extract the value exactly?
I tried with following code, but the comment block prevent me to extract the code. How can extract the value which is inside comment block?
var a = document.getElementsByClassName('hidden_elem')[3].innerHTML;alert(a);
Here's my first attempt, assuming you aren't afraid of a little jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var html = $('.hidden_elem')[0].innerHTML.replace('<!--', '').replace('-->', '');
var href = $(html).find('.itemAnchor').attr('href');
var fbId = getParameterByName('h', href); // fbId = AfjSxEzzdTSrz-pS
Working Demo
EDIT: A way without jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var hiddenElHtml = document.getElementsByClassName('hidden_elem')[0]
.innerHTML.replace('<!--', '').replace('-->', '');
var divObj = document.createElement('div');
divObj.innerHTML = hiddenElHtml;
var itemAnchor = divObj.getElementsByClassName('itemAnchor')[0];
var href = itemAnchor.getAttribute('href');
var fbId = getParameterByName('h', href);
Working Demo
I'd really like to offer a different solution for "uncommenting" the HTML, but I stink at regex :)