Callum Whyte
Callum Whyte

Reputation: 2429

Simultaneous AJAX request with jQuery

I have a search suggestion script that pulls results from two Google APIs, orders the results by an integer value and then displays it to a user.

However, currently the script doesn't appear to return results from the second API until the user has pressed enter or return. Why could this be?

JSFiddle: http://jsfiddle.net/m8Kfx/

My code is:

var combined = [];
$(document).ready(function(){
    $("#search").keyup(function(){
        $("#suggest").html("");
        $.getJSON("http://suggestqueries.google.com/complete/search?q="+$("#search").val()+"&client=chrome&callback=?",function(data){
            for(var key in data[1]){
                if(data[4]["google:suggesttype"][key]=="NAVIGATION"){
                    combined.push("<li rel='"+data[4]["google:suggestrelevance"][key]+"'><a href='"+data[1][key]+"'>"+data[2][key]+"</a></li>");
                }else{
                    combined.push("<li rel='"+data[4]["google:suggestrelevance"][key]+"'>"+data[1][key]+"</li>");
                }
            }
        });
        $.getJSON("https://www.googleapis.com/freebase/v1/search?query="+$("#search").val()+"&limit=3&encode=html&callback=?",function(data){
            for(var key in data.result){
                combined.push("<li rel='"+Math.round(data.result[key].score*5)+"'> Freebase: "+data.result[key].name+"</li>");
            }
        });
        combined.sort(function(a,b){
             return +$(b).attr("rel") - +$(a).attr("rel");
        });
        $("#suggest").html(combined.slice(0, 5).join(""));
        combined = [];
    });
});

Upvotes: 0

Views: 466

Answers (4)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

I noticed two things about the code.

The sorting and appending should be called in the callbacks of the ajax functions, this can be achieved by making another function that handles sorting and display. Then call this function in the success callback.

Second, the freemarker results are showing up, however they are always sent to the bottom of the list. If you view 200 of your results they are at the bottom.

var combined = [];
$(document).ready(function(){
    $("#search").keyup(function(){
        $("#suggest").html("");
        $.getJSON("http://suggestqueries.google.com/complete/search?q="+$("#search").val()+"&client=chrome&callback=?",function(data){
            for(var key in data[1]){
                if(data[4]["google:suggesttype"][key]=="NAVIGATION"){
                    combined.push("<li rel='"+data[4]["google:suggestrelevance"][key]+"'><a href='"+data[1][key]+"'>"+data[2][key]+"</a></li>");
                }else{
                    combined.push("<li rel='"+data[4]["google:suggestrelevance"][key]+"'>"+data[1][key]+"</li>");
                }
            }
            sortAndDisplay(combined);
        });
        $.getJSON("https://www.googleapis.com/freebase/v1/search?query="+$("#search").val()+"&limit=3&encode=html&callback=?",function(data){
            for(var key in data.result){
                combined.push("<li rel='"+Math.round(data.result[key].score*5)+"'> Freebase: "+data.result[key].name+"</li>");
            }
            sortAndDisplay(combined);
        });
    });
});

function sortAndDisplay(combined){
        combined.sort(function(a,b){
             return +$(b).attr("rel") - +$(a).attr("rel");
        });
        $("#suggest").html(combined.slice(0, 200).join(""));
        combined = [];
}

Working Example http://jsfiddle.net/m8Kfx/4/

Upvotes: 0

Sascha Gehlich
Sascha Gehlich

Reputation: 1007

Actually, it does return values, but you have a timing issue here. You fill your list with results, before the requests have actually been finished. Try something like this instead:

http://jsfiddle.net/jDvVL/1/

Also, since you're appending the result of your second request to your array, they will never show up due to your .slice(0,5), so I removed that.

Upvotes: 4

smoore4
smoore4

Reputation: 4866

Wrap the secong getJSON in the first, like this. Nice code BTW.

var combined = [];
$(document).ready(function(){
$("#search").keyup(function(){
    $("#suggest").html("");
    $.getJSON("http://suggestqueries.google.com/complete/search?q="+$("#search").val()+"&client=chrome&callback=?",function(data){
        for(var key in data[1]){
            if(data[4]["google:suggesttype"][key]=="NAVIGATION"){
                combined.push("<li rel='"+data[4]["google:suggestrelevance"][key]+"'><a href='"+data[1][key]+"'>"+data[2][key]+"</a></li>");
            }else{
                combined.push("<li rel='"+data[4]["google:suggestrelevance"][key]+"'>"+data[1][key]+"</li>");
            }
        }

                $.getJSON("https://www.googleapis.com/freebase/v1/search?query="+$("#search").val()+"&limit=3&encode=html&callback=?",function(data){
        for(var key in data.result){
            combined.push("<li rel='"+Math.round(data.result[key].score*5)+"'> Freebase: "+data.result[key].name+"</li>");
        }
    });

    });



    combined.sort(function(a,b){
         return +$(b).attr("rel") - +$(a).attr("rel");
    });
    $("#suggest").html(combined.slice(0, 5).join(""));
    combined = [];
});

});

Upvotes: 0

Dhruval Dave
Dhruval Dave

Reputation: 133

You can do something like this

var allData = []
$.getJSON("/values/1", function(data) {
    allData.push(data);
    if(data.length == 2){
      processData(allData) // where process data processes all the data
    }
});

$.getJSON("/values/2", function(data) {
    allData.push(data);
    if(data.length == 2){
        processData(allData) // where process data processes all the data
    }
});

var processData = function(data){
     var sum = data[0] + data[1]
     $('#mynode').html(sum);
}

Upvotes: 0

Related Questions