By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,481 Members | 3,078 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,481 IT Pros & Developers. It's quick & easy.

Iterate over JSON object

Kelicula
Expert 100+
P: 176
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
Share this Question
Share on Google+
3 Replies


rnd me
Expert 100+
P: 427
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
Expert 100+
P: 176
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
Expert 100+
P: 176
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?input=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

Post your reply

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