Simultaneous AJAX request with jQuery - javascript

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 = [];
});
});

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.

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);
}

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 = [];
});
});

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/

Related

Next iteration of $.each when received AJAX-content

The question has been asked before, but it is almost four years ago and maybe there is a better solution.
I have a $.each-loop where sometimes additional data is being fetched via ajax.
I am bulding an object with the fetched data, after the loop there is a function that generates HTML from the object. The problem is that the loop finishes before the ajax data arrives. If I place an alert in the HTML-generating-function the content is loading properly.
I am searching for a solution that calls the HTML-generator-function only when the loop and all ajax calls are finished. Maybe it is a solution to count the started Ajax requests and wait if all of them are finished?
I believe jQuery deferred is the right solution for me but I do find only examples where everything stays inside the loop. Can someone help?
I have stripped down my code to the most important things:
//goes through each testplace -->main loop
$.each(jsobject, function(key, value)
{
//build object together...
for (var i = 0, numComputer = jenkinsComputer.contents.computer.length; i < numComputer; i++)
{
//If the testplace is in both objects then fire AJAX request
if (jenkinsComputer.contents.computer[i].displayName == key) //<<<This can happen only once per $.each loop, but it does not happen every time
{
//next $.each-iteration should only happen when received the JSON
var testplaceurl = jenkinsComputer.contents.computer[i].executors[0].currentExecutable.url;
$.when($.getJSON("php/ba-simple-proxy.php?url=" + encodeURI(testplaceurl) + "api/json?depth=1&pretty=1")).done(function(jenkinsUser)
{
//build object together...
});
}
}
}); //End of main Loop ($.each)
generateHTML(builtObject);
It would be great if someone could give me an advice how to do it.
I would do something like this:
var thingstodo = $(jsobject).length;
var notfired = true;
$.each(jsobject, function(key, value)
{
//build object together...
for (var i = 0, numComputer = jenkinsComputer.contents.computer.length; i < numComputer; i++)
{
//If the testplace is in both objects then fire AJAX request
if (jenkinsComputer.contents.computer[i].displayName == key) //<<<This can happen only once per $.each loop, but it does not happen every time
{
//next $.each-iteration should only happen when received the JSON
var testplaceurl = jenkinsComputer.contents.computer[i].executors[0].currentExecutable.url;
$.when($.getJSON("php/ba-simple-proxy.php?url=" + encodeURI(testplaceurl) + "api/json?depth=1&pretty=1")).done(function(jenkinsUser)
{
//build object together...
thingstodo--;
if(thingstodo === 0 && notfired){
notfired = false;
generateHTML(buildObject);
}
});
}else{
thingstodo--;
}
}
}); //End of main Loop ($.each)
if(thingstodo === 0 && notfired){
generateHTML(buildObject);
}
This is short untested example about the solution. I hope this to give you idea.
// I guess that jsobject is array ..
// if it is not object you can use something like:
// var keys = Object.getOwnPropertyNames(jsobject)
(function () {
var dfd = $.Deferred();
function is_not_finished() {
return jsobject.length > 0 && jenkinsComputer.contents.computer.length > 0;
}
(function _handleObject() {
var key = jsobject.shift();
var displayName = jenkinsComputer.contents.computer.shift().displayName;
if (displayName == key) //<<<This can happen only once per $.each loop, but it does not happen every time
{
//next $.each-iteration should only happen when received the JSON
var testplaceurl = jenkinsComputer.contents.computer[i].executors[0].currentExecutable.url;
$.getJSON("php/ba-simple-proxy.php?url=" + encodeURI(testplaceurl) + "api/json?depth=1&pretty=1").done(function(jenkinsUser)
{
//build object together...
if(is_not_finished()) {
setTimeout(_handleObject,0);
} else {
dfd.resolve();
}
});
} else if (is_not_finished()) {
setTimeout(_handleObject,0);
} else {
dfd.resolve();
}
}());
return dfd.promise();
}()).done(function () {
generateHTML(builtObject);
});

Parse.com Javascript Asyn Call within Loop

I have a list of company and would like to calculate a total amount of invoices issued to each company. The following is the code that I wrote. (Actual logic is more complicated within the loop but took them out here)
Basically I want to alert the message once the business logic within the loop is complete (Again, it will do something more complex here). I got a feeling that I can resolve this issue by using Promises but am not quite sure how to use it. I didn't quite follow Parse.com's document. I have been stuck with this for a few hours. Please help!
function calculate(companies) {
companies.forEach(function(company) {
var total = 0;
var invoice = Parse.Object.extend('Invoice');
var query = new Parse.Query(invoice);
query.equalTo('invoiceCompany', company);
query.find().then(function(invoices) {
invoices.forEach(function(invoice) {
total += parseFloat(invoice.get('amount'));
});
});
});
alert("Calculated Finished");
}
You can use promises in paralell:
https://parse.com/docs/js/guide#promises-promises-in-parallel
It would be something like this:
function calculate(companies) {
var promises = [];
companies.forEach(function(company) {
var total = 0;
var invoice = Parse.Object.extend('Invoice');
var query = new Parse.Query(invoice);
query.equalTo('invoiceCompany', company);
var queryPromise = query.find().then(function(invoices) {
invoices.forEach(function(invoice) {
total += parseFloat(invoice.get('amount'));
});
});
promises.push(queryPromise);
});
return Parse.Promise.when(promises);
}
calculate(companies).then(function() {
alert("Calculated Finished");
});

Format returned table data in json

I'm fairly new to javascript. I retreive data from a sql server database that looks like this :
[Object { shortcode="0013A2004031AC9A", latest_measurement=1067, keyid="6801"},
Object { shortcode="0013A2004031AC9A", latest_measurement=7, keyid="6802"},
Object { shortcode="0013A2004031AC9A", latest_measurement=8598838, keyid="6803"}]
I want to format this in a json like this :
{mac : 0013A2004031AC9A, keys : {6801:1067, 6802:7, 6803:8598838}}
but I just don't get to that.
I have
var jsonDataPerMac = {};
I loop over the json object above and for every new mac I find I do :
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
but how do I get to fill the keys?
Any hints would be appreciated.enter code here
var macs = [];
var jsonDataPerMac = {};
var i = 0;
$.ajax({
url: "/bmmeasurements",
type: "GET",
data: {"unitid" : unitid},
async: false,
success: function (data) {
console.log(data);
initializeTable();
$.each(data, function (index,device) {
//add all distinct macs in an array, to use them as a column header
if($.inArray(device.shortcode, macs) == -1) {
macs.push(device.shortcode);
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
i++;
//create a table cell for each possible key. id = 'mac-key'
createTableGrid(device.shortcode);
}
//add the measurement data to the correct cell in the grid
$('#' + device.shortcode + '-' + device.keyid).html(device.latest_measurement);
});
}});
Here is my proposition. I would rather avoid using jQuery to perform such a simple operations. In this particular example, we use forEach and for..in loop.
//new output array
var newArray = [];
//we traverse the array received from AJAX call
array.forEach(function(el) {
var added = false; // it's false by default
// we check if the mac is already in newArray, if yes - just add the key
for(var i in newArray) {
if(newArray[i].mac == el.shortcode) {
newArray[i].keys.push(el.keyid+":"+el.latest_measurement);
added = true; // tells us whether the key has been added or not
}
}
// if key hasn't been added - create a new entry
if(!added) {
newArray.push({"mac": el.shortcode, "keys":[el.keyid+":"+el.latest_measurement]});
}
});
console.log(newArray);
You can transform above code to a function and then, reuse it in your ajax onSuccess method. Remember to pass the array as an argument and to return newArray.
JSFiddle:
http://jsfiddle.net/2d5Vq/2/
You need to combine the entries first...
var reducedData = {};
$.each(macs, function(index,macitem){
if (reducedData.hasOwnProperty(macitem.shortcode)) {
reducedData[macitem.shortcode].push(macitem.key);
} else {
reducedData[macitem.shortcode] = [ macitem.key ];
}
});
And then map to your desired format inside an array...
var jsonDataPerMac = [],
i = 0;
$.map(reducedData, function(keys,mac){
jsonDataPerMac[i++] = {"mac": mac, "keys": keys};
// your other code goes here
});
Also your usage of jsonDataPerMac suggests that you want it to be an array.

Why can't jQuery update array data before ajax post?

I am trying to create an array and get all values of a form submission and put them in that array. I need to do this because during the .each function of this code I must do additional encryption to all the values per client. This is a form with hundreds of fields that are changing. So it must be an array to work. I tried to do following and several other types like it in jQuery but no dice. Can anyone help? Thanks.
Edit: Posted my working solution. Thanks for the help.
Edit 2: Accept sabithpocker's answer as it allowed me to keep my key names.
var inputArray = {};
//jQuery(this).serializeArray() = [{name: "field1", value:"val1"}, {name:field2...}...]
jQuery(this).serializeArray().each(function(index, value) {
inputArray[value.name] = encrypt(value.value);
});
//now inputArray = [{name: "field1", value:"ENCRYPTED_val1"}, {name:field2...}...]
//now to form the POST message
postMessages = [];
$(inputArray).each(function(i,v){
postMessages.push(v.name + "=" + v.value);
});
postMessage = postMessages.join('&');
Chack serializeArray() to see the JSON array format.
http://jsfiddle.net/kv9U3/
So clearly the issue is that this in your case is not the array as you suppose. Please clarify what this pointer refers to, or just verify yourselves by doing a console.log(this)
As you updated your answer, in your case this pointer refers to the form you submitted, how do you want to iterate over the form? what are you trying to achieve with the each?
UPDATE
working fiddle with capitalizing instead of encrypting
http://jsfiddle.net/kv9U3/6/
$('#x').submit(function (e) {
e.preventDefault();
var inputArray = [];
console.log(jQuery(this).serializeArray());
jQuery(jQuery(this).serializeArray()).each(function (index, value) {
item = {};
item[value.name] = value.value.toUpperCase();
inputArray[index] = item;
});
console.log(inputArray);
postMessages = [];
$(inputArray).each(function (i, v) {
for(var k in v)
postMessages[i] = k + "=" + v[k];
console.log(i, v);
});
postMessage = postMessages.join('&');
console.log(postMessage);
return false;
});
The problem is that #cja_form won't list its fields using each. You can use serialize() instead:
inputArray = jQuery(this).serialize();
Further edition, if you need to edit each element, you can use this:
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
Full code
jQuery(document).ready(function($){
$("#cja_form").submit(function(event){
$("#submitapp").attr("disabled","disabled");
$("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var input = {};
$(this).find('input, select, textarea').each(function(){
var element = $(this);
input[element.attr('name')] = element.val();
});
$.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', input)
.success(function(result){
if (result.indexOf("success") === -1) {
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail">'+result+'</div>');
}
else {
page = document.URL;
if (page.indexOf('?') === -1) {
window.location = page + '?action=success';
}
else {
window.location = page + '&action=success';
}
}
})
.error(function(){
$("#submitapp").removeAttr('disabled');
$("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
return false;
});
});
Original answer:
There are no associative arrays in javascript, you need a hash/object:
var input = {};
jQuery(this).each(function(k, v){
input[k] = v;
});
Here is my working solution. In this example it adds cat to all the entries and then sends it to the PHP page as an array. From there I access my array via $_POST['data']. I found this solution on http://blog.johnryding.com/post/1548511993/how-to-submit-javascript-arrays-through-jquery-ajax-call
jQuery(document).ready(function () {
jQuery("#cja_form").submit(function(event){
jQuery("#submitapp").attr("disabled","disabled");
jQuery("#cja_status").html('<div class="cja_pending">Please wait while we process your application.</div>');
var data = [];
jQuery.each(jQuery(this).serializeArray(), function(index, value) {
data[index] = value.value + "cat";
});
jQuery.post('../wp-content/plugins/coffey-jobapp/processes/public-form.php', {'data[]': data})
.success(function(result){
if (result.indexOf("success") === -1) {
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail">'+result+'</div>');
} else {
page = document.URL;
if(page.indexOf('?') === -1) {
window.location = page+'?action=success';
} else {
window.location = page+'&action=success';
}
}
})
.error(function(){
jQuery("#submitapp").removeAttr('disabled');
jQuery("#cja_status").html('<div class="cja_fail"><strong>Failed to submit article! Check your internet connection.</strong></div>');
});
event.preventDefault();
event.returnValue = false;
});
});

Simultaneous independent AJAX requests

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. The script ensures it only returns the five most relevant responses for each query based on the rel attribute of each.
JSFiddle: http://jsfiddle.net/22LN5/
However, with this current set-up there is no fault tolerance; for example one API being on available or exceeding the query limit on one API so no results are returned.
How can this be resolved?
My jQuery code is:
var combined=[];
$(document).ready(function(){
$("#search").keyup(function(e){
$(this).html("");
$.getJSON("http://suggestqueries.google.com/complete/search?q="+$("#search").val()+"&client=chrome&callback=?",function(data1){
$.getJSON("https://www.googleapis.com/freebase/v1/search?query="+$("#search").val()+"&limit=3&encode=html&callback=?",function(data2){
for(var key in data1[1]){
if(data1[4]["google:suggesttype"][key]=="NAVIGATION"){
combined.push("<li rel='"+data1[4]["google:suggestrelevance"][key]+"'><a href='"+data1[1][key]+"'>"+data1[2][key]+"</a></li>");
}else{
combined.push("<li rel='"+data1[4]["google:suggestrelevance"][key]+"'>"+data1[1][key]+"</li>");
}
}
for(var key in data2.result){
combined.push("<li rel='"+Math.round(data2.result[key].score*5)+"'> Freebase: "+data2.result[key].name+"</li>");
}
combined.sort(function(a,b){
return +$(b).attr("rel")-+$(a).attr("rel");
});
$("#suggest").html(combined.slice(0,5).join(""));
combined=[];
});
});
});
});
I've updated your fiddle: http://jsfiddle.net/22LN5/2/
I whipped up $.whenFaultTolerant, which will always return the promise in the event of completion or failure. Pass in a hash of deferreds, and out comes a hash of results! This is not a complete solution but I hope it is a good step in the right direction.
$.whenFaultTolerant = function(things) {
var remaining = Object.keys(things).length;
var outputs = {};
var dfd = $.Deferred();
$.each(things, function(key, thing) {
thing.always(function(data) {
outputs[key] = data;
--remaining || dfd.resolve(outputs);
});
});
return dfd.promise();
};
Usage:
$.whenFaultTolerant({
suggestqueries: $.getJSON("http://suggestqueries.google.com/complete/search?q="+$("#search").val()+"&client=chrome&callback=?"),
googleapis: $.getJSON("https://www.googleapis.com/freebase/v1/search?query="+$("#search").val()+"&limit=3&encode=html&callback=?")
}).done(function(data){
console.log(data);
});
Outputs:
{
"suggestqueries": <the results from suggestqueries.google.com>,
"googleapis": <the results from www.googleapis.com>
}

Categories

Resources