Iterate over JSON object

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kelicula
    Recognized Expert New Member
    • Jul 2007
    • 176

    Iterate over JSON object

    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:
    [code=javascript]
    // AJAX CODE //
    // !!!!!!!!!

    var response = 'empty'; // my arbitrary var that decides weather to AJAX or not.


    // My AJAX request function...
    function makeRequest(url ) {
    var httpRequest;

    if (window.XMLHttp Request) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest( );
    if (httpRequest.ov errideMimeType) {
    httpRequest.ove rrideMimeType(' text/xml');
    // See note below about this line
    }
    }
    else if (window.ActiveX Object) { // IE
    try {
    httpRequest = new ActiveXObject(" Msxml2.XMLHTTP" );
    }
    catch (e) {
    try {
    httpRequest = new ActiveXObject(" Microsoft.XMLHT TP");
    }
    catch (e) {}
    }
    }

    if (!httpRequest) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
    }
    httpRequest.onr eadystatechange = function() { response = httpRequest.res ponseText;

    // Here I set the global var response to the JSON object
    // and call the function that updates the div on the page. "updateAjax ()"
    updateAjax();
    };
    httpRequest.ope n('GET', url, true);
    httpRequest.sen d('');

    }

    // THIS is the function that get's called each time a user types a letter...
    function assembleRequest (b) {
    // First make hidden "result" div visible...(cros s browser)
    if(document.get ElementById){
    document.getEle mentById('resul t').style.visib ility='visible' ;
    }
    else if(document.all && !document.getEl ementById){
    document.all.re sult.style.visi bility='visible ';
    }
    // Find out if they have cleared the input field...
    if(b.value){
    if(response == 'empty'){ // If so make new AJAX request...
    makeRequest('aj ax/cityAjax.cgi?ci ty='+b.value);
    }
    // If not just filter through what we already have...
    else{
    updateAjax(b);
    }
    }
    // If they have cleared the field set flag to ensure new AJAX request on next letter entered.
    else{
    response = 'empty';
    }
    }



    // THIS is where the problem is... I need to iterate over the JSON object
    // and use regexe to see if the "city name" field matches...

    function updateAjax(b){

    var inputText = b.value;
    var responseText = response;

    for(responseTex t){

    // WHAT TO DO HERE????
    // I WANT to generate a: "<option value="27603">R aleigh, NC</option>"
    // kinda thing for each element in the JSON object...
    }



    document.getEle mentById("resul t").innerHTM L = responseText;


    }



    // This function just updates the input field to the correct zip, for submitting the form...
    function inputCity(e){

    var it = e.cities.option s[e.cities.select edIndex].value;

    if (it != ""){
    if(document.get ElementById){
    document.getEle mentById('zipco de').value = it;
    document.getEle mentById('resul t').style.visib ility='hidden';
    document.getEle mentById('resul t').blur();
    }
    else if(document.all && !document.getEl ementById){
    document.search Zip.zipcode.val ue = it;
    document.all.re sult.style.visi bility='hidden' ;
    document.all.re sult.blur();
    }

    }
    else{
    alert('Error completing request');
    }
    }

    // END AJAX
    //
    //
    [/code]

    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!
  • rnd me
    Recognized Expert Contributor
    • Jun 2007
    • 427

    #2
    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.

    Comment

    • Kelicula
      Recognized Expert New Member
      • Jul 2007
      • 176

      #3
      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
      [code=javascript]

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

      INTO THIS:
      [code=html]
      <option value="27603">R aleigh, NC</option>
      <option value="25071">E lkview, WV</option>
      [/code]

      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...
      Last edited by Kelicula; Dec 27 '08, 06:57 PM. Reason: double quotes

      Comment

      • Kelicula
        Recognized Expert New Member
        • Jul 2007
        • 176

        #4
        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)

        [code=javascript]
        { "options" : [ { "value" : 45385, "label" : ["Xenia", "OH"]}, { "value" : 62899, "label" : ["Xenia", "IL"] } ] }
        [/code]

        Does this create a buch of options with values of the zip code, and "lables" of the city, state?

        Again I'm reaching for:
        [code=html]
        <option value="45385">X enia, OH</option>
        <option value="62899">X enia, IL</option>
        etc...
        [/code]


        I will attack the regexe, filtering part after this.

        Comment

        Working...