473,671 Members | 2,326 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterate over JSON object

Kelicula
176 Recognized Expert New Member
Hi all,
I am usually a Perl programmer, I have some background in javascript and am attempting to create a Googleish selector div.

Please bear with me, excuse the long introduction...

Here's the details:
Our site filters content by location. I use zip codes to find radius's. So if a user wants to see content from a location that they don't know the zip code for, I have set up this neat little input field that allows you to type the zipcode OR city name.
Once you start typing a city name it queries a database for all cities that "start" with the letters you have entered. Everything worked FINE, but I was noticing a delay due to all the repeated request to my cgi script. (I'm using the onkeyup event to trigger the ajax request.)

SO!!

I had this brite idea to query the database only once on the first letter entered, have the Perl script return a JSON object and use javascript to do the further filtering (On subsequent keyup events)
Only making one AJAX request, and using the data returned from that for further narrowing of result. If the user backspaces to where the input field is empty, then I set an arbitary variable to 'empty' and upon the next letter entered a new AJAX request will be made with the new "first" letter.

So my problem...

How do I iterate over the JSON object returned?

Here is my code so far:
Expand|Select|Wrap|Line Numbers
  1. // AJAX CODE //
  2. // !!!!!!!!!
  3.  
  4. var response = 'empty'; // my arbitrary var that decides weather to AJAX or not.
  5.  
  6.  
  7. // My AJAX request function...
  8. function makeRequest(url) {
  9.         var httpRequest;
  10.  
  11.         if (window.XMLHttpRequest) { // Mozilla, Safari, ...
  12.             httpRequest = new XMLHttpRequest();
  13.             if (httpRequest.overrideMimeType) {
  14.                 httpRequest.overrideMimeType('text/xml');
  15.                 // See note below about this line
  16.             }
  17.         }
  18.         else if (window.ActiveXObject) { // IE
  19.             try {
  20.                 httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
  21.                 }
  22.                 catch (e) {
  23.                            try {
  24.                                 httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  25.                                }
  26.                              catch (e) {}
  27.                           }
  28.                                        }
  29.  
  30.         if (!httpRequest) {
  31.             alert('Giving up :( Cannot create an XMLHTTP instance');
  32.             return false;
  33.         }
  34.         httpRequest.onreadystatechange = function() { response = httpRequest.responseText;
  35.  
  36. // Here I set the global var response to the JSON object
  37. // and call the function that updates the div on the page. "updateAjax()"
  38.                                                       updateAjax();
  39.                                                         };
  40.         httpRequest.open('GET', url, true);
  41.         httpRequest.send('');
  42.  
  43.     }
  44.  
  45. // THIS is the function that get's called each time a user types a letter...
  46.     function assembleRequest(b) {
  47. // First make hidden "result" div visible...(cross browser)
  48.     if(document.getElementById){
  49.             document.getElementById('result').style.visibility='visible';
  50.             }
  51.             else if(document.all && !document.getElementById){
  52.             document.all.result.style.visibility='visible';
  53.             }
  54. // Find out if they have cleared the input field...
  55.     if(b.value){
  56.         if(response == 'empty'){ // If so make new AJAX request...
  57.         makeRequest('ajax/cityAjax.cgi?city='+b.value);        
  58.         }
  59. // If not just filter through what we already have...
  60.         else{
  61.         updateAjax(b);
  62.         }
  63.     }
  64. // If they have cleared the field set flag to ensure new AJAX request on next letter entered.
  65.     else{
  66.     response = 'empty';
  67.     }
  68.     }
  69.  
  70.  
  71.  
  72. //  THIS is where the problem is... I need to iterate over the JSON object
  73. // and use regexe to see if the "city name" field matches...
  74.  
  75.     function updateAjax(b){
  76.  
  77.         var inputText = b.value;
  78.         var responseText = response;
  79.  
  80.         for(responseText){
  81.  
  82.        // WHAT TO DO HERE????  
  83.        // I WANT to generate a: "<option value="27603">Raleigh, NC</option>"
  84.        //  kinda thing for each element in the JSON object...
  85.         }
  86.  
  87.  
  88.  
  89.         document.getElementById("result").innerHTML = responseText;
  90.  
  91.  
  92.     }
  93.  
  94.  
  95.  
  96. // This function just updates the input field to the correct zip, for submitting the form...
  97.     function inputCity(e){
  98.  
  99.     var it = e.cities.options[e.cities.selectedIndex].value;
  100.  
  101.     if (it != ""){
  102.             if(document.getElementById){
  103.             document.getElementById('zipcode').value = it;
  104.             document.getElementById('result').style.visibility='hidden';
  105.             document.getElementById('result').blur();
  106.             }
  107.             else if(document.all && !document.getElementById){
  108.             document.searchZip.zipcode.value = it;
  109.             document.all.result.style.visibility='hidden';
  110.             document.all.result.blur();
  111.             }
  112.  
  113.     }
  114.     else{
  115.     alert('Error completing request');
  116.    }
  117. }
  118.  
  119. // END AJAX
  120. //
  121. //
  122.  
The JSON object returned from my Perl script is in this format:

$json = {
27603 : Raleigh : NC,
25071 : Elkview : WV,
10001 : New York : NY,
etc....
};


How can I get to the city name field, and see if it matches the text entered by the user???

Any help would be greatly appreciated!!!

I had it working perfectly (albeit slowly and erratically) before I tried to use the JSON, and reponse flag var.

Thanks!
Dec 27 '08 #1
3 6885
rnd me
427 Recognized Expert Contributor
thats not a valid json structure.

it would be easiest to use an array of strings using a comma to separate the state.

that way, you can easily loop through the array and find partial matches.


make sure the json structure works when pasted into firebug's console.

i can draw up a iteration code for you if you get a working json posted.
Dec 27 '08 #2
Kelicula
176 Recognized Expert New Member
OK, I guess I should be asking; "How would I create an associative array in json?".
I need to know, the city name, the state and the zip code in order to create select options.

e.g.

TURN
Expand|Select|Wrap|Line Numbers
  1.  
  2. var json = { 27603 : [ "Raleigh", "NC"] , 25071 : [ "Elkview", "WV"] };
  3.  
INTO THIS:
Expand|Select|Wrap|Line Numbers
  1. <option value="27603">Raleigh, NC</option>
  2. <option value="25071">Elkview, WV</option>
  3.  
Then AFTER that I can learn how to iterate over the structure...

:)


OR would it be easier to assemble it this way:

var json = { "Raleigh" : [ 27603, "NC"], "Elkview" : [ 25071, "WV"] };

I can have the Perl script return any type of format, I have chose json over XML because I believed it would be easier to manipulate with JavaScript.

actually I could just have it return a javascript array, but I would need three of them?!
Ahhh!!

Now I'm confused...
Dec 27 '08 #3
Kelicula
176 Recognized Expert New Member
OK, did some reeading, and altering of my perl script, I think I have it outputting a correct json object.

Here is the output when passing the letter "x" to the makeRequest function.

(actually "cityAjax.cgi?i nput=x" to be exact)

Expand|Select|Wrap|Line Numbers
  1. { "options" : [ { "value" : 45385, "label" : ["Xenia", "OH"]}, { "value" : 62899, "label" : ["Xenia", "IL"] } ] }
  2.  
Does this create a buch of options with values of the zip code, and "lables" of the city, state?

Again I'm reaching for:
Expand|Select|Wrap|Line Numbers
  1. <option value="45385">Xenia, OH</option>
  2. <option value="62899">Xenia, IL</option>
  3. etc...
  4.  

I will attack the regexe, filtering part after this.
Dec 27 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

20
6848
by: Luke Matuszewski | last post by:
Welcome As suggested i looked into JSON project and was amazed but... What about cyclical data structures - anybody was faced it in some project ? Is there any satisactional recomendation... PS i am ready to use JSON as data/object interchange when using AJAX and my J2EE project - because it is easier to traverse the JavaScript object than its XML representation (so of course may argue).
2
3744
by: Kevin Newman | last post by:
Hello, I noticed that the JavaScript library for JSON posted on json.org (http://www.json.org/json.js) is modifying Object.prototype (adding a method - toJSONString). I thought this was considered bad practice because it can disrupt the use of for in loops on Objects. Am I incorrect? Thanks,
3
10170
by: Adam | last post by:
I'm trying to retrieve some values from a json object, but instead it's giving me the property name. For example: var json = { "glossary": { "title": "example glossary" } }; console.log(json); alert(json.glossary.title); for (var x in json) { console.log(x); alert(x.title); } This will show me the json object in the console with glossary and title underneath it. When the alert for json.glossary.title fires, it
2
3313
by: ChrisO | last post by:
I've been pretty infatuated with JSON for some time now since "discovering" it a while back. (It's been there all along in JavaScript, but it was just never "noticed" or used by most until recently -- or maybe I should just speak for myself.) The fact that JSON is more elegant goes without saying, yet I can't seem to find a way to use JSON the way I *really* want to use it: to create objects that can be instantated into multiple...
23
3196
by: dhtmlkitchen | last post by:
JSON We all know what it is. In ECMAScript 4, there's a JSON proposal: Object.prototype.toJSONString String.prototype.parseJSON The current proposal, String.prototype.parseJSON, returns an object.
25
25437
RMWChaos
by: RMWChaos | last post by:
Any JSON experts out there? I'd like to know if it is possible, and if so how, to iterate through a JSON property list so that each iteration selects the next value for each object. Here is an example list: function myFunction() { createDOM({ 'id' : , 'dom' : , 'parent' : "content", 'form' : ,
15
7720
RMWChaos
by: RMWChaos | last post by:
As usual, an overly-long, overly-explanatory post. Better too much info than too little, right? A couple weeks ago, I asked for some assistance iterating through a JSON property list so that my code would either select the next value in the member list or the single value. The original post can be found here. This is the code gits helped me write: for (var i = 0; i < attribList.id.length; i++) { var attrib = {};
4
8869
by: im12345 | last post by:
I have the following question: Im doing a sample application using dojo and json. I have 2 classes: 1. Book class package com.esolaria.dojoex; import org.json.JSONObject; import org.json.JSONException;
9
10866
by: Jon Paal [MSMD] | last post by:
using json like ( {"Records": , "RecordCount":"1" } ) and jquery like: $.ajax({ .... success: function(json, status) {
0
8472
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8667
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7428
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6222
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5690
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4221
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2806
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2048
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1801
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.