JavaScript - If Class Is, Get The Info From Xml Or Json
I am currently working on a project that requires pretty large bits of jQuery (atleast for me) and once I get this function working I can solve more required functions but I have problems getting this to work.
Basically what im trying to do is, when a link is clicked (within a certain div) it reads out the class of that link and searches within XML or JSON for the title and then finds the description within that record. I hope someone is able to point to the right direction, Thanks in advance, Mehk. Similar TutorialsJust starting to look at Handlebars.js today and wanted a clear approach. Assume the following: We don't have control over how the JSON was created (So no server side solutions). JSON will have 1 or more records in it. In each record, there will be a Message_Type name/value pair the value of which would be useful in some function which css class(es) are used in the presentation. ex: message_type: basic, ad, notification, warning, critical. Each message_type will have a css class. So critical message type might get classes .msg_box .critical_msg. How should I do this (remember, we can't change the original source).? Option 1: process json data before handlebars and add name/value pair for each that contains the appropriate classes, or some way in handle bars. I have a very large json file, and inside of that json file is an array. I would like to use JavaScript to take that json as an argument, parse through the json and only take certain elements from it and put it into a new json file, below is an example of what I mean: Code: { "contextType": "Account", "preferences": null, "custodianCode": null, "data": [{ "id": "0", "account": "11111111", "field2": true, "field3": false, "field4": "BROK", "field5": "Broker", "field6": "1", "field7": "Cash" },{ "id": "1", "account": "222222222", "field2": true, "field3": false, "field4": "BROK", "field5": "Broker", "field6": "1", "field7": "Cash" }] } And I want to pull from that and get something like this as a new json Code: { "newArray": [{ "id": "0", "account": "11111111", "field2": true, "field3": false, "field4": "BROK", "field6": "1" },{ "id": "0", "account": "222222222", "field2": true, "field3": false, "field4": "BROK", "field6": "1" }] } Also the file is local to my computer and can be outputted locally as well, I am trying to use node.js and JavaScript this is what I have so far Code: var json = require('./simple.json'); var keeperFields = ["id", "account", "field2", "field3", "field4", "field6"]; var newJSON = {newArray: [] }; var i; var fields; for (i = 0; i < keeperFields.length; i++) { for (fields in json) { if (json.hasOwnProperty(keeperFields[i])) { newJSON.newArray.push(keeperFields[i]); } } } console.log(newJSON); This is just a small example the real json file is huge with thousands of lines. Any help or suggestions are appreciated! This current solution is giving me a console log of { newArray: []} instead of the expected result above Hello, I am new with Javascript and running into this problem that I don't understand. I define a base class that only contains an array "elements", and a derived class that contains nothing more (for simplicity): Code: function baseClass() { this.elements = new Array; } function derivedClass() { } derivedClass.prototype = new baseClass; Then I create two instances of the derived class, and add two elements in each: Code: a = new derivedClass(); a.elements.push("A"); a.elements.push("B"); b = new derivedClass(); b.elements.push("C"); b.elements.push("D"); When I examine the contents of these arrays, I see that both a.elements and b.elements contain {"A","B","C","D"} ! I.e. as if the two arrays are in fact the same array! But these are two separate instances of the class, I expect two separate arrays. Note that if instead I use the base class: Code: a = new baseClass(); a.elements.push("A"); a.elements.push("B"); b = new baseClass(); b.elements.push("C"); b.elements.push("D"); then I get a.elements = {"A","B"} and b.elements = {"C","D"}, as I would expect. Could someone explain to me the problem with using the derived class? Thank you, Stephanos Hello all, I thought I'd share something that I don't see talked about much on the forums. I've been doing a bunch of AJAX development at work. We're really strapped for processing speed on our client (we build the machines our clients use) and therefore we've needed to find ways of speeding everything up. One of the things we decided on within the first week of our current project was to completely scrap XML in favor of JSON for sending data back and forth. JSON is JavaScript Object notation. Many of you have already seen it, it looks like this: Code: {'prop1' : 'someValue', 'prop9' : 5}; That defines an object with 2 properties, prop1 and prop9, with the respective values "someValue" and 5. Compare that to XML: Code: <obj> <prop1 value="someValue" type="String" /> <prop2 value="5" type="Integer" /> </obj> That's a bit more bloated, maybe not too noticeable, but the example is a small one. If you take large amounts of data, and multiple objects, XML can get incredibly bloated, and bloat on the wire slows down your app. That's the first reason we switched. The second reason we switched is that we save time on the processing. We all know what it's like to get at XML data. Import the document, get the node, get the value, get the next node, get the value. And building XML documents can take just as long: Create document, create root node, create node, create attribute node, set value, append child, repeat... All that processing for something so simple. JSON on the other hand is a subset of javascript, so check this out. Code: var data = "{'prop1':'someValue', 'prop2':5}"; var obj = eval("(" + data + ")"); alert(obj.prop1); // *** Alerts 'someValue' *** The string fits right into JavaScript in one function call. Granted, eval can be expensive, but if you test this out yourself, it's far cheaper than building and deconstructing XML in the JavaScript engine. There are 2 simple JSON parsing libraries that we use in development: JSON.php and json.js; these provide the necessary functions to serialize any PHP object into JSON, and serialize any JavaScript object into JSON. You can get them at the links below. We are also following the specification for JSON-RPC, defined in the last link below. We found this to be incredibly fast when compared to XML, and we haven't regretted it yet. Granted, we're not doing full blown web services where the the javascript modifies itself based on the service's self-definition, complete with namespaces and function signatures, but we transfer a lot of data quickly and efficiently to provide our users with the best experience possible. I recommend examining this further if you do AJAX development. Hopefully this helped somebody. http://json.org/ http://mike.teczno.com/json.html http://json-rpc.org/ And now for the "VS" part of this post: Anyone with experience in using both XML and JSON that wants to argue the mertis of either technique? I support JSON for almost all AJAX applications currently. I haven't found a good reason to use XML, and the negatives for using XML (bloat and processing speed) have currently knocked it completely from my "viable options" list. Anyone care to discuss? Hi I have some JSON strings and I want to embed it into my website. The problem is that I don't know how to parse JSON string data into html code. After a long search it seem that there is just a few references and manuals about JSON. Could someone explain to me how to use this function and also with as many examples as possible for understanding, how to put it into html page. Thank You I am making a dynamic google map and need to pass in a JS Object that has latitude, longitude, address, name, and a link. The JS Object will be getting those values from a DB and may have up to 15 recordsets. I need to know how to separate that out into it's entities to include in the Map API regardless of how many recordsets there are.
I'm trying to get a return of Code: [ ["red","green","blue"] ,["blue","red","green"] ] from a text file that contains Code: red,green,blue blue,red,green Using the following function Quote: Originally Posted by Old Pedant Code: function WRITE_FILE_AS_JSON(file) { fso = Server.CreateObject("Scripting.FileSystemObject"); myPath=Server.MapPath("timecards/" + file); if(!fso.FileExists(myPath))return; myfile = fso.OpenTextFile( myPath, read); var lines = myfile.readAll().split("\n"); Response.Write("[\n"); for ( var i = 0; i < lines.length; ++i ) { Response.Write(' ' + (i >0 ? ',' : '' ) + '["' + lines(i).replace(/\,/g,'","') + '"]\n'); } Response.Write("]\n"); myfile.Close(); Response.End(); } The darn thing keeps returning Quote: 500 (Internal Server) Error as a result of the line Response.Write(' ' + (i >0 ? ',' : '' ) + '["' + lines(i).replace(/\,/g,'","') + '"]\n'); And I don't know how to fix that line... All, Say I have the following code: Code: <!DOCTYPE html> <html> <head> <style>img{ height: 100px; float: left; }</style> <script src="http://code.jquery.com/jquery-1.7rc2.js"></script> </head> <body> <div id="images"> </div> <script> $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { tags: "cat", tagmode: "any", format: "json" }, function(data) { $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); });</script> </body> </html> This came from the jQuery website. What I would like to do is change the link to something like this: https://graph.facebook.com/me/friend...ss_token=12345 The data that comes back is something like: Code: { "data": [ { "review_comment": "Here is a comment", "id": "12" }, { "review_comment": "Testing With more", "id": "34" }, { "review_comment": "Third comment", "id": "643" }, { "review_comment": "More Comments", "id": "120" }, { "review_comment": "Testing", "id": "3455" } ] } What I would like to do is basically read all of the review_comment tags and basically rotate these to display them on the webpage. So have "Here is a comment" be displayed for like 10 seconds and then fade out and have "Testing with More" fade in and be displayed for another 10 seconds etc. What is the best way to do this? I'm not sure how to change my JSON code above to acheive this. Would I need to basically put the comments in a div and then use jQuery to fade in the divs in and out? Any help you could provide would be greatly appreciated!! hello i am using a json file to import some content into a div like this: Code: $.getJSON('json/main_profile.json', function(data) { $('#info_title').html( '<h1>' + "General Information " + '</h1>' ); }); but the problem appears when i try to replace the json file with a url, like this: Code: $.getJSON("http://interfaces-server.insource.local/users/145198", function(data) { $('#info_title').html( '<h1>' + "General Information " + '</h1>' ); }); why works with the file but not with the link?? thanks I've been using the JSON.stringify method to convert my JSON object to a string to pass via AJAX but I've read now that it is not supported in most browsers. What then should I use?
hey guys im trying to create this script which will show array depending on what option has been selected on the select box...but the only thing being returned is "unidentified"....can anyone explain where i am going wrong please...thank you Code: <!DOCTYPE html> <html> <head> <script type="text/javascript" src="/ajax/jquery/libary/jquery.js"></script> </head> <body> <?php $game_type = array(); $division = array(); if ($_POST['game'] == 1) { $game_type[] = array('value' => '1', 'text' => 'TDM' ); $game_type[] = array('value' => '1', 'text' => 'CTF' ); $division[] = array('value' => '1', 'text' => 'Divison 1' ); } elseif ($_POST['game'] == 2) { $game_type[] = array('value' => '1', 'text' => 'CTF' ); $division[] = array('value' => '1', 'text' => 'Divison 2' ); } json_encode($game_type); json_encode($division); ?> <form> <script> $(document).ready(function(){ $("select#game").change(function(){ var post_string = "game=" + $(this).val(); $.ajax({ type: 'POST', data: post_string, cache: false, dataType: 'json', url: 'json.php', timeout: '2000', error: function() { alert("Error has occured"); }, success: function(data) { $.each(data, function(i, j){ var row = "<option value=\"" + j.value + "\">" + j.text + "</option>"; $(row).appendTo("select#sub_category"); }); } }); }); }); //$('#game_type').html('<input type=\"checkbox\" value=\"test\" /> TDM'); //$('#division').html('<input type=\"checkbox\" value=\"test\" /> Division 1'); </script> <select name="game" id="game"> <option value=""></option> <option value="1">Counter Strike</option> <option value="2">COD</option> </select> <div id="game_type"> </div> <div id="division"> </div> <select name="sub_category" id="sub_category"> <option value="">-- Select First Value --</option> </select> </form> </body> </html> i have a variable $page that is storing code similar to this PHP Code: onloadRegister(function (){Quickling.init("329319;0", 10, {"page_cache":1,"quickling_init_page":false,"flush_cache_in_transition":1,"flush_cache_in_page_write":0});}); onloadRegister(function (){JSCC.init({"j4d235b8b8399023097431421":function(){return new AsyncLayout();}}, false);}); onloadRegister(function (){JSCC.init({"j4d235b8b8399023097431422":function(){return new SearchDataSource({"maxResults":8,"queryData":{"viewer":100000503667042},"queryEndpoint":"\/ajax\/typeahead\/search.php","bootstrapData":{"viewer":100000503667042,"token":"1294162702-5","lfe":1},"bootstrapEndpoint":"\/ajax\/typeahead\/first_degree.php"});},"j4d235b8b8399023097431423":function(){return new Typeahead(JSCC.get('j4d235b8b8399023097431422'), {node: $("u282757_1"), ctor: "SearchTypeaheadView", options: {"autoSelect":true,"renderer":"search"}}, {node: $("q"), ctor: "SearchTypeaheadCore", options: {"keepFocused":false,"resetOnSelect":true}}, $("u282757_2"))}}, false);}); onloadRegister(function (){window.__UIControllerRegistry["c4d235b8b883d27291189921"] = new UIPagelet("c4d235b8b883d27291189921", "\/pagelet\/profile\/tux_toolbar.php", {"profile_id":100000503667042,"sk":"wall"}, {});; ;}); onloadRegister(function (){ft.enableFeedTracking();}); onloadRegister(function (){JSCC.get('j4d235b8b8399023097431421').init($("contentArea"), $('rightCol'), $('headerArea'), $('toolbarContainer'));}); onloadRegister(function (){window.loading_page_chrome = true;}); PHP Code: $page = curl_exec($curl_handle); $d = json_decode($page); $profileid = $d['profile_id']; htmlOut("kevins profile id = ".$profileid); function htmlOut($var){ echo "<hr /><b>".$var."</b><hr />"; } This is what i have but its not isolating the profile id does anybody know how i can do this please the id im looking for is 100000503667042 thanks for any help provided. the "count" field/value on this JSON example for the MarkerClusterer app http://google-maps-utility-library-v.../src/data.json http://gmaps-utility-library.googlec.../examples.html i am trying to produce a similar JSON result and i cant figure out where their "count" variable is calculated at 10785236 for... but the following does not work Code: var data = { "count": 2, "photos": [{"photo_id": 1, "photo_title": "testing", "photo_url": "http://www.site.com/photo/522084", "photo_file_url": "http://www.site.com/avatars/test.jpg", "longitude": -97.6765157, "latitude": 31.1482230, "width": 500, "height": 350, "upload_date": "7 September 2010", "owner_id": 1, "owner_name": "b747fp", "owner_url": "http://www.site.com/user/1"} , {"photo_id": 2, "photo_title": "testing", "photo_url": "http://www.site.com/photo/522084", "photo_file_url": "http://www.site.com/avatars/test.jpg", "longitude": -118.4104684, "latitude": 34.1030032, "width": 500, "height": 350, "upload_date": "7 September 2010", "owner_id": 4, "owner_name": "test", "owner_url": "http://www.site.com/user/4"} ] } hihi i am doing a project regarding ajax how am i going to call the title because normally if you call start year is like var detail = eval.... then for loop it inside should be var start year="" startyear += ...[i].startyear something like this but how am i going to call the title inside the note? Code: { "infos": { "info": [ { "startYear": "1900", "endYear": "1930", "timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..", "timeZoneID": "1", "note": { "notes": [ { "id": "1", "title": "Mmm" }, { "id": "2", "title": "Wmm" }, { "id": "3", "title": "Smm" } ] }, "links": [ { "id": "1", "title": "Red House", "url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html" }, { "id": "2", "title": "Joo Chiat", "url": "http://www.the-inncrowd.com/joochiat.htm" }, { "id": "3", "title": "Bake", "url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery" } ] } In IE, the output is as expected, all four values print to the page. In every other rendering engine, the title data does not, neither of them. This is really quite simple I can't understand what the issue could be. No errors showing in any browser. function JSONpop() { var JSONtest = {"items": [ { "title": "sample 1", "author": "author 1" }, { "title": "sample 2", "author": "author 2" } ]}; var testClass = document.getElementsByTagName('div')[0].getAttribute('class'); if(testClass=="news-story") { document.getElementsByTagName('div')[0].childNodes[0].innerHTML = JSONtest.items[0].title; document.getElementsByTagName('div')[0].childNodes[1].innerHTML = "By: "+JSONtest.items[0].author; document.getElementsByTagName('div')[0].childNodes[2].innerHTML = JSONtest.items[1].title; document.getElementsByTagName('div')[0].childNodes[3].innerHTML = "By: "+JSONtest.items[1].author; } } I have been able to parse a JSON feed before but forwhatever reason this time around I am having a hell of a time getting it working. Here is where I am at right now. So far the script dosn't output anything. Code: <table width="100%" border="0" cellspacing="0" cellpadding="10"> <script> xhttp=new XMLHttpRequest(); xhttp.open("GET","http://biz104.inmotionhosting.com/~cox7co5/api/get_category_posts/?id=5",false); xhttp.send(""); json_data=xhttp.responseText; var parsed_data = eval('('+json_data+')'); var slug="stuff" for (i=0;i<parsed_data.count;i++) { document.write("<tr><td><a href=\"#\" class=\"showlist\">"+parsed_data.posts[i].title+"</a></td><tr>"); } </script> </table> I'm quite new to javascript programming, I basically want to parse a JSON string from an external URL. http://cashtrackr.com/piwik/index.ph...9d8d472cc9974a This is the json string URL and I just want to output the contents of "nb_visits" for example. I would also like to know the terms for a JSON string "?" : ? thanks for your time hi there i need your help. i would like to build a small poll. client should receive the data from server (a JSON file). client will load the data. It'll send the selection to the server, after the user has acted. The poll should look like this. **** are you a linux user? Yes No **** Yes and No with radio buttons. So the end result should look like this..If i open a website, the page will be dynamically created and it'll load the data ("are you a linux user?") from the server. The selection will be sent to the server where this saves the selection. Hope someone could help me out with this? I am going through the example at the bottom of this page: http://api.jquery.com/jQuery.getJSON/ I am using the following code: Code: <!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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script src="http://code.jquery.com/jquery-1.4.4.js"></script> </head> <body> <script> var id=$("#id").attr("value"); $.getJSON("json.php",{id:id},dates); function dates(datos) { $("#list").html("Town:"+datos[1].rsTown+"<br>"+"County:"+datos[1].rsCounty); } </script> <div id="id"></div> <div id="list"></div> </body> </html> and I'm trying to pull my JSON data from my PHP page: http://www.mypubspace.com/dashtest/json.php the JQuery seems to be doing something but nothing is being output to my screen?! project page http://www.mypubspace.com/dashtest/json.html Please help?! a simple NO YOU CAN'T or a BUY A TEXTBOOK & READ IT will probably answer my query.. what i want to do is to analyse a load of share bulletin boards, from a webpage on my home pc. i'd hoped to do it by putting the bb page in an iframe and parsing the iframe's innerHTML. but this is barred by javascript. i'm a bit cheesed off having found that out only after doing the hard work of writing the parsing-code.. (i had pasted a sample bulletin board source code into the iframe, so it was all local..) but i read something about JSON.. which might outflank the security. i'd like to know: can i get an example of how this might be done? how much of a learning curve is JSON. can i fix it up on this machine? thanks for any help.. |