Adam
Adam

Reputation: 1299

JSON response will not append to div

I have this <script>:

// autocomplet : this function will be executed every time we change the text
function autocomplet() {
    var min_length = 0; // min caracters to display the autocomplete
    var keyword = $('#stock_name').val();
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'search',
            type: 'POST',
            dataType: 'application/json',
            data: {keyword:keyword},
            success:function(data){
                $('#stock_list').show();
                $('#stock_list').html(data);
            }
        });
    } else {
        $('#stock_list').hide();
    }
}
// set_item : this function will be executed when we select an item
function set_item(item) {
    // change input value
    $('#stock_name').val(item);
    // hide proposition list
    $('#stock_list').hide();
}

And when using Google Chrome Dev tools i can see that i´am getting a response:

{aktie: "Hoist Finance AB"}, {aktie: "Holmen AB ser. A"}, {aktie: "Holmen AB ser. B"}]
0: {aktie: "Hoist Finance AB"}
1: {aktie: "Holmen AB ser. A"}
2: {aktie: "Holmen AB ser. B"}

And I want to show the JSON respons in a div, but it just won't show up!

    <div class="content">
        <form>
            <div class="label_div">Type a Stock : </div>
            <div class="input_container">
                <input type="text" id="stock_name" onkeyup="autocomplet()">
                <ul id="stock_list">asd</ul>
            </div>
        </form>
    </div>

I have tried append, val and a few other from the jQuery docs, but nothing.

My question: How do i show the JSON respons that i get, in the div stock_list?

Upvotes: 2

Views: 102

Answers (2)

Bfcm
Bfcm

Reputation: 2746

Define function for Success like following.

Change your html code to:

success:onSuccess

Then define function onSuccess() :

function onSuccess(data) {
    $('#stock_list').show().html("");
    $.each(data, function() {
            $("#stock_list").append("<li>" + this.aktie + "</li>");
        });
    }
}

Upvotes: 3

RiccardoC
RiccardoC

Reputation: 866

Your json data must be parsed. Edited after @Bfcm answer, that was much better

        success:function(data){
            $('#stock_list').show().html( "" );
            $.each(data, function() {
              $("#stock_list").append("<li> + this.aktie + "</li>");
            });
        }

Upvotes: 0

Related Questions