fizzy drink
fizzy drink

Reputation: 682

JSON results not returning correctly. Unexpected results. jQuery + Ajax + JSON

I have an <input> field that, when you start to type in something, a live ajax result is returned with the result, kind of like "Auto suggest" except that, instead of in the <input>, the results are displayed in a <div>. The problem is that it does not return the results in an expected fashion. It only seems to return one result, the "last" one if you will. Below is code I found on the net and adapted to suit my needs.

so I have the following HTML

<input class="getter" id="search" name="search" type="text" value="" /> 
<div class="data" id="results">
    Gonzo
</div>

and the following JavaScript

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
    $(document).ready(function() {

        $('#search').keyup(function() {
            var q = $(this).val();
            var regex = new RegExp(q, "i");
            var count = 1;
            var output = '';
            $.getJSON('http://www.fizzydrink.eu/alice.json', function(data) {
                $.each(data, function(key, val) {
                    if ((val.name.search(regex) != -1)) {
                        output = val.name + val.color;
                        if(count%2 == 0) {
                            output = '<p></p>';
                        }
                        count++;
                    }
                });
                $('#results').html(output);
            });
        });

    });
</script>

You can find a demo on jsFiddle. Also, attached below is the raw JSON file:

[
    {"name":"alice","color":"red","at":"@alice"},
    {"name":"albert","color":"cyan","at":"@albert"},
    {"name":"bob","color":"green","at":"@bob"},
    {"name":"bertrand","color":"purple","at":"@bertrand"},
    {"name":"peter","color":"blue","at":"@peter"}
]

Upvotes: 0

Views: 42

Answers (1)

Stryner
Stryner

Reputation: 7318

You are creating an output variable:

output = '';

But instead of concatenating, you are constantly replacing it with a new string:

//Instance 1
output = val.name + val.color;

//Instance 2
output = '<p></p>';

Instead you should be adding to it:

//Explicitly
output = output + val.name + val.color;

//Shorthand (does exactly the same as the line above)
output += val.name + val.color;

Upvotes: 1

Related Questions