JavaScript - Handlebars.js Json Setting Class(es) Based On Value/pair
Just 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. Similar TutorialsI 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. I have set if sentence when form is validate like: {if $smarty.request.action == "form1"} {nocache} {literal} <script type="text/javascript"> document.location='replyfile'; </script> {/literal} {/nocache} {/if} 1. How to retrieve values with Smarty as fields have value in name='' ...'' as now it does not capture value in form. 2. How to send form ONLY when all fields are validated? I have currently: {if $smarty.request.action == "form1"} and send button like: <input type="submit" name="form" value="Send my messages" class="mybutton" /> How to send after validation is performed? 3. This should mean sending form when name="form1" is clicked. Is it if sentence correct set with name form1? Application is: http://bassistance.de/jquery-plugins...in-validation/ Version 1.7. Now is sending when I click on button but it should send values and after validation is made. Ok...so here is what I have: Code: function myClass() { this.checkLogin = function(name,pwd) { if(name.length > 0 && pwd.length > 0) { $.ajax({async: false, type: "post", url: "url", dataType: "json", data: "data", success: this.parseData}); } } this.parseData = function(data) { this.status = data.status; alert(this.status); } this.getStatus = function() { alert(this.status); } } Everything works above. The first alert shows that this.status was set to 'error'. However, if I call myClass.getStatus(), I get undefined. How can I get the parseData function to set the variables in the parent function? Thanks! thanks anyway
I'm trying to add a body class of 'day' if it's 6am-5pm and 'night' if it's 5pm-6am based on the user's local time. I tried the following but it didn't work. Any ideas? In the <head> Code: <script> function setTimesStyles() { var currentTime = new Date().getHours(); if(currentTime > 5 && currentTime < 17) { document.body.className = 'day'; } else { document.body.className = 'night'; } } </script> Code: <body onload="setTimeStyles();"> Also, is there a more elegant way to achieve what I need? 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 Hi, What's a good way/ideal data structure to achieve this? The objective of the code/function is to map user-inputted strings into a pair of specific, hard-coded strings. For example, say the user types "firefox" or "ff", or "fx". The output would be the pair ["browser", "mozilla"], for example. I'm currently using a multidimensional array, but it feels inefficient and I'm having trouble mapping an arbitrary number of inputs into 2 outputs. Code: var strings = [ ["input1", "output1a"], ["input2", "output1a"], ["input3", "output1a"], ["input1", "output1b"], ["input2", "output1b"], ["input3", "output1b"] ]; How should I map the elements ["input1", "input2", "input3"] => ["output1a", "output1b"] ? Another method I used previously was a massive switch statement. This fulfills my needs, but I'm not sure about the efficiency (though if I remember correctly, switch statements become more efficient as size grows, since it uses a hash table?). Code: switch (input) { case "ff": case "firefox": case "fx" : case "ffox": return ["browser", "mozilla"]; case "ie": case "internet explorer": return ["browser", "microsoft"]; ... } 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? 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?
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.
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!! 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... 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> 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" } ] } 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 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. |