Search code examples
javascriptjqueryget

synchronous method in javascript and $.get method in jQuery


I have a strange issue with my method :

$('#search').on('keyup', function () {
    var valNow = $('#search').val();
    if (last !== valNow && valNow !== '') {
        console.log(valNow + ' / ' + i);
        //interrogate a server from a cities
        $.get(path + '/' + strategy() + '/' + valNow,
            function (data, status) {
                //here
                console.log(status);
                if (status === 'success') {
                    cities = [];
                    cities = data;
                }
            },
            'json');
        // make new last
        last = valNow;
        //list result
        var items = [];
        console.log(cities[0]);
        console.log(' / ' + i);
        $(cities).each(function (index, value) {
            console.log(value);
            var notStrong = valNow.length;
            var strong = value.length;
            items.push('<li><strong>'+ valNow +'</strong>'+value.substr(notStrong)+'</li>');
        });
        $('.result').append(items).show();
        i++;
        console.log('finished');
                  }
             }
        );

the problem is simply when I use (/bind) this function I get finish message before console.log(status) (commented://here), the $.get function takes a lot of times to interrogate the web service , I don't know why I have this issue with $.get function, is it a thread or something like this ??? what I want is to get in order all statements (console.log(status) then console.log('finish')).


Solution

  • Try appending your options inside the function block which gives you the data

    $('#search').on('keyup', function () {
    var valNow = $('#search').val();
    if (last !== valNow && valNow !== '') {
        console.log(valNow + ' / ' + i);
        //interrogate a server from a cities
        $.get(path + '/' + strategy() + '/' + valNow,
            function (data, status) {
                if (status === 'success') {
                    cities = data;
                    // append all the options here
                 }
            },'json');
         }
       }
    );