1

The Story So far....

Trying to learn JS and JQuery and i thought i would start with the basics and try alittle AJAX "search as you type" magic. Firstly i just wanted to get the AJAX part right and iterating through the return JSON object and appending it to a unordered list. Im doing no validation on the inputted value vs. the returned JSON results at this time, i just want a controlled way of when to do the AJAX getJSON call. Later i will do the validation once i get this right.

Anyways im having trouble displaying the Account Numbers in in the ul. At the moment the only thing that is being displayed is AccountNumber in the li and not my ACCOUNT NUMBERS

My JS Code is here:

http://jsfiddle.net/garfbradaz/HBYvq/54/

but for ease its here as well:

$(document).ready(function() {
$("#livesearchinput").keydown(function(key) {
    $.ajaxSetup({
        cache: false
    });
    $.getJSON(" /gh/get/response.json//garfbradaz/MvcLiveSearch/tree/master/JSFiddleAjaxReponses/", function(JSONData) {
        $('<ul>').attr({
            id: "live-list"
        }).appendTo('div#livesearchesults');
        $.each(JSONData, function(i, item) {
            var li = $('<li>').append(i).appendTo('ul#live-list');
            //debugger;
        });

    });



});

});​

My JSON file is hosted on github, but again for ease, here it is:

https://github.com/garfbradaz/MvcLiveSearch/blob/master/JSFiddleAjaxReponses/demo.response.json

{

   "AccountNumber": [

      1000014,

      1015454,

      1000013,

      1000012,

      12

   ]

}

Also here is my Fiddler results proving my JSON object is being returned.

enter image description here

EDIT:

There were so queries about what i was trying to achieve, so here it goes:

  1. Learn JQuery
  2. To build a "Search as you Type" input box. Firstly i wanted to get the AJAX part right first, then i was going to build an MVC3 (ASP.NET) Application that utilises this functionality, plus tidy up the JQuery code which includes validation for the input vs. the returned JSON.

Cheesos answer below worked for me and the JSFiddle can be found here:

http://jsfiddle.net/garfbradaz/JYdTU/

garfbradaz
  • 3,424
  • 7
  • 43
  • 70

3 Answers3

2

First, I think keydown is probably the wrong time to do the json call, or at least... it's wrong to do a json call with every keydown. That's too many calls. If I type "hello" in the input box, within about .8 seconds, then there are 5 json requests and responses.

But you could make it so that it retrieves the json only the first time through, using a flag.

Something like this:

$(document).ready(function() {
    var $input = $("#livesearchinput"), filled = false;
    $.ajaxSetup({ cache: false });
    $input.keydown(function(key) {
        if (!filled) {
          filled = true;
          $.getJSON("json101.js", function(JSONData) {
            var $ul =
            $('<ul>')
                .attr({id: "live-list"})
                .appendTo('div#livesearchesults');
            $.each(JSONData, function(i, item) {
                $.each(item, function(j, val) {
                  $('<li>').append(val).appendTo($ul);
                });
            });
          });
        }
    });
});

The key thing there is I've used an inner $.each().

The outer $.each() is probably unnecessary. The JSON you receive has exactly one element in the object - "AccountNumber", which is an array. So you don't need to iterate over all the items in the object.

That might look like this:

            $.each(JSONData.AccountNumber, function(i, item) {
                $('<li>').append(item).appendTo($ul);
            });
Cheeso
  • 189,189
  • 101
  • 473
  • 713
  • So this will execute on the first keydown and then never again? – Dvir Jun 14 '12 at 21:03
  • How is that the expected behavior? Call `.getJSON` on the first key being typed and then ignore any more input? – Dvir Jun 14 '12 at 21:14
  • I don't know what you mean by "how is that the expected behavior?" I have no idea what the "expected behavior" is, but I believe that sending a HTTP GET for each keydown, and then *appending* the response to an HTML element on the page, is probably NOT what he wants. It's more likely he was doing that as an attempt to diagnose a situation he didn't understand. I don't know what exactly the OP wants, and it's possible he doesn't know what exactly he wants either. I'm just trying to be helpful here. – Cheeso Jun 14 '12 at 21:28
  • That's great and you did it well by providing a great answer, but your addition about 'filled' flag will make the event execute once for the first keydown and then never again. Do you see what I mean? – Dvir Jun 14 '12 at 21:32
  • Yes, Dvir, I see what you mean; I inserted the flag purposefully, specifically for that reason. The get/append on subsequent keydowns was not helping to diagnose the situation. – Cheeso Jun 14 '12 at 22:05
  • @Cheeso: I will give this a whirl tonight. Thank you for your comprehensive answer, very much appreciated. I will edit my original question so you know my ultimate goal for wanting to learn this. – garfbradaz Jun 15 '12 at 08:22
1

What you probably want is this:

    $.each(JSONData.AccountNumber, function(i, item) {
        var li = $('<li>').append(item).appendTo('ul#live-list');
    });
Ryan Kinal
  • 17,414
  • 6
  • 46
  • 63
0

Your code:

$.each(JSONData, function(i, item) {
    var li = $('<li>').append(i).appendTo('ul#live-list');
});

Says "iterate over the keys and values of the outer JSON structure, and print the keys". The first key is "AccountNumber", so you end up printing that.

What you want to do is iterate over the array stored at JSONData.AccountNumber, and print the values:

$.each(JSONData.AccountNumber, function() {
    var li = $('<li>').append(this).appendTo('ul#live-list');
});
Eric
  • 95,302
  • 53
  • 242
  • 374
  • Thank you for your answer Eric, and for explaining where my code is going wrong, very much appreciated. Along with Cheeso and Ryan answer tonight, i will try yours as well. Very much appreciated. – garfbradaz Jun 15 '12 at 08:24
  • Hi Eric. Firstly sincere apologies for the delay in replying. I amended my JSFiddle didnt work: http://jsfiddle.net/garfbradaz/HBYvq/65/ Doesnt worry as Cheesos response worked below, but thanks for helping, appreciated. – garfbradaz Jun 18 '12 at 18:03