score:1
I think the cleanest way is to push the results from each dataset into an externally scoped variable, then sort and render from that. Example is below.
var combined = [],
completed = 0;
$(document).ready(function () {
$("#search").keyup(function () {
combined = [];
completed = 0;
$.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({
href : data[1][key],
text : data[2][key],
score : parseInt(data[4]["google:suggestrelevance"][key],10)
});
} else {
combined.push({
text : data[1][key],
score : parseInt(data[4]["google:suggestrelevance"][key],10)
});
}
}
if ( ++completed == 2 ) complete();
});
$.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({
text : data.result[key].name,
score : parseInt(data.result[key].score,10) * 14
});
}
if ( ++completed == 2 ) complete();
});
});
});
function complete(){
console.log(combined);
combined.sort(function(a,b){ return b.score - a.score; });
var buffer = [];
combined.forEach(function(result){
buffer.push("<li>"+result.text+" <i>("+result.score+")</i></li>")
})
$("#suggest").html(buffer.join(""));
}
Edit
This solution doesn't take into account the fact that the user may be typing at a faster pace than the APIs, that API calls may not come back in order, and doesn't do anything to try to limit the number of calls made to each API. To make this behave more consistently (and more efficiently):
- Change the keypress handler such that each key press cancels any previous timeouts then sets a new timeout at a reasonable delay (300ms seems a reasonable place to start) which then triggers the API calls
- Wrap each API call in an immediately executed function so that you can reference the value of a global counter at the time each API call was made. Increment the counter with each keypress, and don't process the response from API calls where the counter didn't match
Similar question
- How to set variable from JSON results array
- JSON response returns 2 out of 3 date results as Objects, not as strings
- Autocomplete: display results with json data
- How to submit data to external website using JSON /JQUery and get the results and display in my JSP page
- using AJAX results variable throughout code
- How to handle '00' in JSON results in JS or Coldfusion
- Backbone: Feed JSON in a variable instead of fetching through URL
score:0
score:0
Put them together and sort.
Following is the code.
Using promise to know both ajax requests are completed.
$(document).ready(function(){
$("#search").keyup(function(){
var mergedData = [];
var promise1 = $.getJSON("http://suggestqueries.google.com/complete/search?q="+$("#search").val()+"&client=chrome&callback=?",function(data){
var suggestion="";
console.log(data);
var arr = [];
for(var i in data[1]){
arr[i] = {value : data[1][i], rel : data[4]['google:suggestrelevance'][i]};
}
$.extend(mergedData,arr);
arr.sort(function(a, b){
return (b['rel']-a['rel']);
});
});
var promise2 = $.getJSON("https://www.googleapis.com/freebase/v1/search?query="+$("#search").val()+"&limit=3&encode=html&callback=?",function(data){
console.log('data of second request', data);
var suggestion2="";
var arr = [];
for(var key in data.result){
arr[key] = {value : data.result[key].name, rel : data.result[key].score};
}
$.extend(mergedData,arr);
$("#suggest2").html(suggestion2);
});
$.when(promise1, promise2).then(function(){
mergedData.sort(function(a, b){
return (b['rel']-a['rel']);
});
var suggestion = '';
for(var key in mergedData){
suggestion+='<li>' + mergedData[key].value + ' ' + mergedData[key].rel + '</li>';
}
$("#suggest").html(suggestion);
});
});
});
Updated working jsfiddle : http://jsfiddle.net/rEPf3/13/
score:1
Here is the full code for you, you have to append all the results to one container and sort in .ajaxComplete
event
$(document).ready(function () {
$("#search").keyup(function () {
$("#suggest").empty();
$.getJSON("http://suggestqueries.google.com/complete/search?q=" + $("#search").val() + "&client=chrome&callback=?", function (data) {
var suggestion = "";
for (var key in data[1]) {
if (data[4]["google:suggesttype"][key] == "NAVIGATION") {
suggestion += "<li><a href='" + data[1][key] + "'>" + data[2][key] + "</a> <i>(" + data[4]["google:suggestrelevance"][key] + ")</i></li>";
} else {
suggestion += "<li>" + data[1][key] + " <i>(" + data[4]["google:suggestrelevance"][key] + ")</i></li>";
}
}
$("#suggest").append(suggestion);
});
$.getJSON("https://www.googleapis.com/freebase/v1/search?query=" + $("#search").val() + "&limit=3&encode=html&callback=?", function (data) {
var suggestion2 = "";
for (var key in data.result) {
suggestion2 += "<li>" + data.result[key].name + " <i>(" + data.result[key].score * 4 + ")</i></li>";
}
$("#suggest").append(suggestion2);
});
$(document).ajaxComplete(function (event, xhr, settings) {
$("#suggest").html($("#suggest li").sort(function (a, b) {
return (parseInt($(a).find("i").html(), 10) > parseInt($(b).find("i").html(), 10));
}));
});
});
});
Related Query
- Quotes are escaped when passing JSON as a POST variable
- Why does the order keep changing when appending repeated results from a json iteration?
- Merge JSON values into a variable or string
- jquery printing json object using .each shows more results than expected
- use JSON variable in jQuery to display more JSON variables
- Setting Div Content to property of JSON Object results in html tags showing on screen
- How can I pass Json data to autocomplete sourece variable
- jQuery image resizing - over a variable and directly gives different results
- How to overload Json in asp.net mvc for custom results
- Global variable lost which results on failure during function assigning
- Select2 Not Showing the Results of Json
- jQuery Datatables: Pass returned JSON to a variable
- Read Json Variable
- JSON object ordering being tampered with by jQuery or Javascript
- json variable is undefined
- Can you pass a variable as part of a JSON chain
- JSON encode MySQL results then read using jQuery
- Json String with comment out quotes in variable
- jQuery - Concatenate string with integer to create pre-existing variable
- Enter data into JSON variable
- Store all the keys of a JSON object in a variable
- Convert Date Format in JSON variable
- Jquery set how to set a global variable json post
- Loading JSON into JavaScript variable locally without server-side script?
- parsing json by jquery's getJSON for twitter api search results not working
- Can I use a variable to pass a json string?
- Insert Javascript (jquery) variable in a JSON string
- jquery store json object from url in javascript variable
- extract single variable from JSON array
- Parsing MySQL JSON results in Jquery
- Incrementing an integer in javascript results in NaN
- jquery syntax for making positive variable integer negative
- Accessing JSON value results in undefined
- Ordering results in PHP search suggestions
- Dynamically populate JSON array from variable value
- JSON variable undefined when global
- Loading JSON into variable via getJSON
- Returning JSON with jQuery .post results in "undefined"
- Having trouble looping a JSON file to create manipulatable results to populate a drop down list
- Weird results from JSON returned array
- JavaScript - Building of JSON data structure - How to change key name with variable value
- jQuery JSON database variable applied in Javascript
- How to use a variable as a json atribute?
More Query from same tag
- Accessing dynamically generated elements
- Best "store locator" - "map" jQuery plugin?
- Toggle on and off with jQuery
- How to use JS to control what is returned by an included HTML file?
- jQuery Parents and Data
- Script for detecting height and changing padding
- jquery ajax not parsing json data from php
- how to group list elements using jquery
- jquery toggle between ID's based on element attribute
- Checking all inputs after un-checking them all
- Click event firing but .fadeIn not working
- IE 11 still submits form without .submit() inside click handler
- make a new DOM object a button in jquery ui
- Fixed headers with css transitions
- Hide div is child is empty
- Button loading and control property not getting changed on form submit
- jQuery - product quantity not changing when I click plus button
- jQuery callback function not working for cross domain
- on window resize change div height
- How make a loop using JQUERY?
- Selenium code to extract text/find only visible elements with "one" class
- Replace a jQuery object path part with variable
- Auto focus needs refresh to work
- how to switch class between two elements using jQuery
- How do I open a div then close it again with a changing text button
- JQuery text box click function that increments value even when text box is empty
- Best way to show .mov on a website as load screen
- Ajax: link in ajax response is not working
- can we call a database using AJAX?
- Using submithandler (Jquery Validate ) to submit a form upon validation