.each loop only returning last result - javascript

My .each of alphabet is only returning the last result on "s" in:
$('#keywordTable tr:last').after('<tr><td>' + s + '</td><td>' + val[0] + '</td><td>0</td><td>0</td><td>0</td></tr>');
relevant javascript code:
var suggestCallBack; // global var for autocomplete jsonp
var keywordCount = 0;
var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789".split("");
$('body').on("click", '#submit', function() {
$('#keywords').html('');
var search_input = $("#keyword").val();
var language = $("#edit-domain").val();
callAPI(search_input, language);
_.each(alphabet, function(letter) {
callAPI(search_input + ' ' + letter);
callAPI(letter + ' ' + search_input);
});
return false;
});
function callAPI(s, language){
$.getJSON("http://suggestqueries.google.com/complete/search?callback=?", {
"hl": language, // Language
//"ds":"yt", // Restrict lookup to youtube
"jsonp": "suggestCallBack", // jsonp callback function name
"q": s, // query term
"client": "youtube" // force youtube style response, i.e. jsonp
});
suggestCallBack = function(data) {
var suggestions = [];
var languageText = $("#edit-domain option:selected").text();
$('#keywordTable').show();
$.each(data[1], function(key, val) {
suggestions.push({
"value": val[0],
});
$('#keywordTable tr:last').after('<tr><td>' + s + '</td><td>' + val[0] + '</td><td>0</td><td>0</td><td>0</td></tr>');
$('#keywordCount').text(++keywordCount);
$('#keywordtext').text(s);
$('#languageholder').text(languageText);
});
}
}
Here is a live preview: http://keyworda.com
The problem: (circled in red): http://i.imgur.com/gR46SuE.png

You are running into a problem with multiple simultaneous JSONP requests. Each of your callback function names must be different, or else they are overwriting each other and you'll only see the last request's result. You can read more about that here or here.
To fix your $.getJSON call you should remove the jsonp: 'suggestCallback' bit and give the callback function as the second parameter instead. The callback name is automatically filled by jQuery, because you put callback=? in the URL.
$.getJSON("http://suggestqueries.google.com/complete/search?callback=?", {
"hl": language, // Language
"q": s, // query term
"client": "youtube" // force youtube style response, i.e. jsonp
}, function(data){
var suggestions = [];
var languageText = $("#edit-domain option:selected").text();
$('#keywordTable').show();
$.each(data[1], function(key, val) {
suggestions.push({
"value": val[0],
});
$('#keywordTable tr:last').after('<tr><td>' + s + '</td><td>' + val[0] + '</td><td>0</td><td>0</td><td>0</td></tr>');
});
});
Here's some working code: http://plnkr.co/edit/O2JKhhOziRczIMkctQc7?p=preview

Related

ajax weird bahavior in url after deleting data in browsers cache

I have a C# Webservice which I'm contacting through URL to retrieve data. The Webservice is lying on a local server in our company network. For example: I have a specific function to get street names, the url to webservice is like this :
Request URL:http://10.1.1.32:8080/webportale_ger_webservice.asmx/SelectStreets
This URL is stored in localStorage.
After deleting browsers cache the request URL has changed, which makes absolutly no sense to me:
http://10.1.1.32:8081/nullSelectStreets
The port is wrong and what about that null?
After trying this request several times again, the url value changes to the correct value.
My jQuery ajax Request looks like this:
var UrlToWebservice = window.localStorage.getItem("url_to_webservice");
$(document).on("keyup", "#input_strasse", function () {
var inputStr = $('#input_strasse').val();
var charStr = inputStr.charAt(0).toUpperCase() + inputStr.substr(1);
console.log("buchstabensuppe: ", charStr)
$.ajax({
type: 'POST',
url: UrlToWebservice + 'SelectStreets',
data: { 'charStr': charStr },
crossDomain: true,
dataType: 'xml',
success: function (response) {
$("input_strasse_datalist").empty();
var strassen = new Array;
$(response).find('STRASSE').each(function () {
var strasse = $(this).find('NAME').text();
var plz = $(this).find('PLZ').find('plz').text();
var ort = $(this).find('PLZ').find('ORT').text();
var arstrasse = $(this).find('AR').first().text();
console.log("arstrasse ", arstrasse)
$("#input_strasse_datalist").append('<option data-ar = ' + arstrasse + ' value = "' + strasse + ' (' + plz + ', ' + ort + ')">' + strasse + ' (' + plz + ', ' + ort + ')</option>')
$("#input_plz").val(plz)
$("#input_ort").val(ort)
})
},
error: function () {
window.location.hash = "httperror";
}
})
})
The value in localStorage is: http://10.1.1.32:8080/webportale_ger_webservice.asmx/
What am I doing wrong?
Thanks a lot.

Utilising the same ajax data for a "refresh all" event (wanting to prevent multiple calls)

So I have a page where multiple containers are dynamically added and filled with html, some of which are populated with data pulled via ajax from a json file. Every 5 minutes the page runs a function that gets every container (marked with class) and for each of them works out its id/index (probably not very efficiently) and does the ajax post.etc.
But the ajax call resulting data is the same essentially for every instance (no limit but on average there would be ~30 ajax calls of the same data for one whole page), it grabs it, decodes it, sorts it, updates html and that is it really.
This feels clunky and im sure will cause issues down the line, is there anything I can do to prevent these 30+ ajax posts without disabling it being 'Asynchronous'/lessen the impact of it?
setInterval(function() {
$('.fill').each(function() {
var selectId = this.id;
var selectIdNum = selectId.replace(/\D/g, '');
selectedId = 'selectedcoin' + selectIdNum;
var index = document.getElementById(selectedId).selectedIndex;
$.ajax({
url: 'array-to-json.php',
type: 'POST',
dataType: 'json',
success: function(data) {
data.sort(function(a, b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
});
result = data;
var php1 = [result[index].name, result[index].symbol, result[index].price_btc, result[index].percent_change_24h, result[index].price_usd, result[index].id, result[index]['24h_volume_usd']];
var myCoinCost = parseFloat($('#buyprice' + selectIdNum).val());
var myPercCoin = (parseFloat(php1[2]).toPrecision(20) - myCoinCost) / myCoinCost * 100;
var myCoinTotal = parseFloat($('#coins' + selectIdNum).val());
var myUsdCoin = myCoinTotal * parseFloat(php1[4]).toPrecision(20);
$("#price" + selectIdNum).html(php1[2]);
$("#pricePercent" + selectIdNum).html(php1[3]);
$("#priceUsd" + selectIdNum).html(php1[4] + "</span>");
$("#volDay" + selectIdNum).html("$" + php1[6] + "</span>");
$("#myPercent" + selectIdNum).html(myPercCoin.toFixed(2) + "%");
$("#myEarnings" + selectIdNum).html(myUsdCoin.toFixed(2));
},
error: function() {
alert("error");
}
});
});
}, 300 * 1000);
It seems like your call returns all the data for all the containers already. You don't pass any specific ID into it, and you are filtering the results when you get them, so I will make that assumption.
In that case, all you need to do is move your .each loop inside the ajax success function. That way the ajax runs once, and you just loop through the data when it's received to apply it to the HTML.
I think this should do it:
setInterval(function() {
$.ajax({
url: 'array-to-json.php',
type: 'POST',
dataType: 'json',
success: function(data) {
data.sort(function(a, b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
}); //is this really necessary? The server-side could probably sort it more efficiently, esp if it's the result of the SQL query.
result = data;
$('.fill').each(function() {
var selectId = this.id;
var selectIdNum = selectId.replace(/\D/g, '');
selectedId = 'selectedcoin' + selectIdNum;
var index = document.getElementById(selectedId).selectedIndex;
var php1 = [
result[index].name, result[index].symbol,
result[index].price_btc, result[index].percent_change_24h,
result[index].price_usd, result[index].id,
result[index]['24h_volume_usd']
];
var myCoinCost = parseFloat($('#buyprice' + selectIdNum).val());
var myPercCoin = (parseFloat(php1[2]).toPrecision(20) - myCoinCost) / myCoinCost * 100;
var myCoinTotal = parseFloat($('#coins' + selectIdNum).val());
var myUsdCoin = myCoinTotal * parseFloat(php1[4]).toPrecision(20);
$("#price" + selectIdNum).html(php1[2]);
$("#pricePercent" + selectIdNum).html(php1[3]);
$("#priceUsd" + selectIdNum).html(php1[4] + "</span>");
$("#volDay" + selectIdNum).html("$" + php1[6] + "</span>");
$("#myPercent" + selectIdNum).html(myPercCoin.toFixed(2) + "%");
$("#myEarnings" + selectIdNum).html(myUsdCoin.toFixed(2));
});
},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
}, 300 * 1000);

Can't Grab Query String in JavaScript

We were provided function getQueryStringVariableByItemID for our project and are using function getData to use a web service for a game's details from a games table. We believe the getData part is working fine since we use a similar POST on another page. Is getQueryStringVariableByItemID not properly grabbing the query string?
We call getData with the body tag of html as onload="getData()". Many thanks in advance!
Code:
<script type="text/javascript">
function getQueryStringVariableByItemID(ItemID) {
//use this function by passing it the name of the variable in the query
//string your are looking for. For example, if I had the query string
//"...?id=1" then I could pass the name "id" to this procedure to retrieve
//the value of the id variable from the querystring, in this case "1".
ItemID = ItemID.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + ItemID + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function getData() {
var ItemID = getQueryStringVariableByItemID(ItemID)
$.ajax({
type: "POST",
url: "./WebServiceTry.asmx/GetGameDetails",
data: "{'ItemID': '" + escape(ItemID) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.d;
$('#output').empty();
$.each(data, function (index, item) {
var Title = item.Title
var Price = "$" + item.Price
var Year = "Year: " + item.Year
var Developer = "Developer: " + item.Developer
var Platform = "Platform: " + item.Platform
$('#output').append('<li>' + Title + '</li>');
$('#output').append('<li>' + Price + '</li>');
$('#output').append('<li>' + Year + '</li>');
$('#output').append('<li>' + Developer + '</li>');
$('#output').append('<li>' + Platform + '</li>');
$('#output').listview('refresh');
});
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</script>
The ItemID you are passing in the getData(while calling inside the getData) should be undefined because the function doesnt have that variable.Pass a valid id and it will work fine

How to name and reuse a javascript function

I have the following bit of jQuery code that i want to reuse by calling it from other parts of my jQuery code. How would i do that?
$(document).ready(function() {
$('#share_mention').charcount({
maxLength: 140,
preventOverage: false
});
$('.countable').bind('update', function(evt, length, remaining) {
var message = 'id=' + $(evt.target).attr('id') + ', length=' + length + ', remaining=' + remaining;
});
});
There are many ways to skin this cat but here is an approach.
var yourNameSpace = {};
yourNameSpace.YourFunction = function(){
$('#share_mention').charcount({
maxLength: 140,
preventOverage: false
});
$('.countable').bind('update', function(evt, length, remaining) {
var message = 'id=' + $(evt.target).attr('id') + ', length=' + length + ', remaining=' + remaining;
});
}
$(document).ready(function() {
yourNameSpace.YourFunction()
});
First things first there is no such thing as a jQuery function. It's a javascript function.
The event is implicitly passed to the callback function.
function countCats (event) {}
$('.cats').on('click', countCats);

Another jQuery autocomplete issue

So, i have read at least 20-30 auto complete problems here on so and i cannot find any solutions. For some odd reason i keep getting value = undefined. Here is my code.
//Cycles through each input and turns it into a person searcher.
$.each(settings.input, function() {
var input = $(this);
input.autocomplete({
delay: 70,
minLength: 2,
source: function(req, add) {
var val = input.val();
$.post(VUI.SITE_URL + "scripts/autocomplete/_AutoComplete.php", {q: val, display_count: settings.displayCount, action: "user"}, function(data) {
data = eval("(" + data + ")");
if (data.length > 0) {
var results = new Array(data.length);
$.each(data, function(key, value) {
results[key] = {desc: value, value: value.firstname + " " + value.lastname};
});
add(results);
} else {
add(["No results..."]);
}
});
},
select: function(event, ui) {
alert(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
}
}) // end auto complete.
.data("autocomplete")._renderItem = function($ul, item) {
var $li = $("<li></li>"),
$inner = $("<div class='st-display side-content clearfix'style='padding-top:6px'></div>"),
$a = $("<a></a>"),
$img = $("<div class='image fl'></div>").html(ST.Image.getImage({
uid: item.desc.uid,
type: ST.ST_IMAGE_TYPE_THUMBNAIL_SMALL
})),
$content = $("<div class='content fl'></div>").html(
item.desc.firstname + " " + item.desc.lastname + "<br/>" +
"<span class='color:#979797;font-weight:bold'>" + item.desc.city + ", " + item.desc.state + "</span>"
);
$inner.append($img).append($content);
$a.append($inner);
$li.append($a);
$ul.append($li);
return $ul;
} // end _renderItem */
I tried to make it so that its very straight forward. But it wont work! (its facebook like auto complete). The auto complete displays properly (item does not equal undefined at that point), but when i highlight it, item becomes undefined so item.value (line 6347 of jquery.ui.1.8.13) throws exception!
Anyone see problems?
Here is something interesting... When i do not use data("autocomplete")._renderItem (for custom completion) the selecting works! ... So why does overriding the custom rendering cause issues? I am even returning the UL.
The only thing in your code that's different from a working version I've got of something very similar is that I initialise $li with:
var $li = $( '<li></li>' ).data('item.autocomplete', item);
That attaches the data to the list item which I think the autocomplete plugin uses to get the value at selection time.
Hope it helps

Categories