Issue with Related Post Javascript in Blogger - javascript

I have created a related post javascript for blogger.com based blogs. The related post plugins loops though the label attached to the current post and displays other posts with the same label.
You can find that in action # http://www.techquark.com/2017/07/infocus-turbo-5-affordable-powerful.html
The issue is I want to skip the current post to be shown in the related post, but unable to achieve the same.
PFB the javascript code :
$(".related-ready").each(function() {
var b = $(this).text();
$.ajax({
url: "/feeds/posts/default/-/" + b + "?alt=json-in-script&max-results=3",
type: 'get',
dataType: "jsonp",
success: function(e) {
var u = "";
var h = '<div class="related">';
for (var i = 0; i < e.feed.entry.length; i++) {
for (var j = 0; j < e.feed.entry[i].link.length; j++) {
if (e.feed.entry[i].link[j].rel == "alternate") {
u = e.feed.entry[i].link[j].href;
break
}
}
var g = e.feed.entry[i].title.$t;
var c = e.feed.entry[i].content.$t;
var $c = $('<div>').html(c);
if (c.indexOf("//www.youtube.com/embed/") > -1) {
var p = e.feed.entry[i].media$thumbnail.url;
var k = p
} else if (c.indexOf("<img") > -1) {
var q = $c.find('img:first').attr('src');
var k = q
} else {
var k = NO_IMAGE
}
h += '<li><div class="related-thumb"><a class="related-img" href="' + u + '" style="background:url(' + k + ') no-repeat center center;background-size: cover"/></div><h3 class="related-title">' + g + '</h3></li>'
}
h += '</div><div class="clear"/>';
$(".related-ready").html(h);
$('.related-img').each(function() {
$(this).attr('style', function(i, src) {
return src.replace('/default.jpg', '/hqdefault.jpg')
}).attr('style', function(i, src) {
return src.replace('s72-c', 's1600')
})
})
}
})
});
TIA !

You will need to check whether the current Post's ID matches with the ID of the post in feed and then skip that post, the code will look like -
....
for (var i = 0; i < e.feed.entry.length; i++) {
if(e.feed.entry[i].id.$t.split("post-")[1] === "<data:post.id/>"){
break;
}
for (var j = 0; j < e.feed.entry[i].link.length; j++) {
....

Related

Nested loop only rendering last indexed item using jquery appendPe

Performing an ajax call to a drinks api and I've nested a loop to pull the ingredients out and render them to the page. The nested loop consoles the ingredients correctly but when I use jquery to append the results to the page only the item in the last index is displayed. I know there are null values I was going to remove them with an if statement after I got them to show.
function displayDrinkData(drinkName) {
var queryURL = "https://thecocktaildb.com/api/json/v1/1/search.php?s=" + drinkName
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
var results = response.drinks;
for (var i = 0; i < results.length; i++) {
console.log(results[i]);
var eachDrink = results[i];
var drinkDiv = $("<div>");
var drinkName = results[i].strDrink;
for (var k = 1; k < 16; k++) {
console.log(eachDrink['strIngredient' + k]);
var ingList = $("<ul>").text("Ingredients: " + eachDrink['strIngredient' + k])
}
var pOne = $("<p>").text("Drink name: " + drinkName);
var drinkInstructions = results[i].strInstructions;
var pTwo = $("<p>").text("Instructions: " + drinkInstructions);
var drinkImage = $("<img>");
drinkImage.attr("src", results[i].strDrinkThumb);
drinkDiv.append(pOne);
drinkDiv.append(ingList);
drinkDiv.append(pTwo);
drinkDiv.append(drinkImage);
$("#drinks-view").append(drinkDiv);
}
})
}
Because var ingList is inside loop, not appending, but creating a new one every time.
var ingList = $("<ul>");
for (var k = 1; k < 16; k++) {
console.log(eachDrink['strIngredient' + k]);
ingList.append($('<li>').text("Ingredients: " + eachDrink['strIngredient' + k]));
}
Declare variable outside loop, and append <li> for each element.

Javascript for loop only giving one output

I've been toying with this for far too long...
function OnSearch() {
var text_in = sVal()
var tArea = document.getElementById("SearchResults")
var loadstr = "Loading results for "
var xhttp = new XMLHttpRequest();
var altStr = ""
var sendstr = ""
var urls = []
for (i = 0; i < ciphersOn.length; i++) {
aCipher = ciphersOn[i]
sendstr += "/search="+text_in+""
sendstr += '/name=' + aCipher.Nickname + ''
sendstr += '/letters='
for (x = 0; x < aCipher.cArr.length; x++) {
sendstr += String.fromCharCode(aCipher.cArr[x])
}
sendstr += "/cipher="
for (x = 0; x < aCipher.vArr.length; x++) {
if(aCipher.vArr.length == x+1){
sendstr += aCipher.vArr[x]
} else sendstr += aCipher.vArr[x] + "-"
}
/* send http GET and bring back info to a new list, then clear sendstr before it loops again. */
urls.push(sendstr)
sendstr=""
}
for(i = 0; i < urls.length; i++) {
xhttp.open("GET", "http://localhost:8000" + urls[i] + "", true);
xhttp.send();
}
loadstr += '"' + text_in + '"' + sendstr + '' + urls.length + '' + aURL + '' /* the purpose of this is so I can see what is happening to my code */
tArea.innerHTML = loadstr
}
I have no clue why that for loop at the end only sends one GET request. Please, spare me my sanity... I just don't get it. The array "urls" contains the information I need, and the variable "sendstr" works perfectly well... Why then does my terminal only show that the first result is being given?
Each XMLHttpRequest can only send one request. As stated in MDN, calling open on an already open request is equivalent to aborting the request. So, create a new XMLHttpRequest for each loop:
for(i = 0; i < urls.length; i++) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8000" + urls[i], true);
xhttp.send();
}
Alternatively, migrate to fetch:
for(i = 0; i < urls.length; i++) {
fetch("http://localhost:8000" + urls[i]);
}

Jquery ajax send json

Javascript:
function add_content(count)
{
var result = {};
var row = new Array();
for (i = 0; i < count; i++)
{
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}
$.ajax({
url: "ajax-functions.php",
data: {json_data: JSON.stringify(row)},
type: 'post',
success: function (output) {
alert(output);
}
})
}
Php:
$img_desc = json_decode($_POST['json_data'],TRUE);
$count = count($img_desc);
echo 'count:'.$count;
print_r($img_desc);
I want to send json to from JS to PHP. This above code works well, but it send the last data of the for loop is set in all the objects.
How to fix it? Is this right way?
Thanks.
Push a new object on each round of the loop into to the array
for (var i = 0; i < count; i++) {
row.push({
"img_src": $("#img_" + i).attr('src'),
"desc": $("#desc_" + i).val()
});
}
fiddle
Move result declaration inside for:
var row = new Array();
for (i = 0; i < count; i++)
{
var result = {};
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}
or it can be done more elegantly:
var row = new Array();
var result;
for (i = 0; i < 10; i++)
{
result = row[ row.push({}) - 1 ];
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
}
You can make the keys of result array also dynamic
Since you are not making it dynmamic, its getting over ridden in the next loop
EDIT:
for (i = 0; i < count; i++)
{
var result = {};
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}

How to get rid of double for loop in autocomplete

I am currently making an autocomplete function that retrieves a bunch of information encoded by JSON and allows the user to search through it. There is a slight delay in the search results, and I think that a for loop inside of another for loop is the cause of this issue. Below is the Javascript file:
var username = [];
var businessname = [];
var fname = [];
var lname = [];
var fullname = [];
var clientid = [];
var bankArray = [];
var data_for_post = [];
var focusedArrayElement = "";
var started = false;
var currentSelectedList = 0;
var searchString = "";
$(document).keydown(function(event) {
switch(event.keyCode) {
case 40:
if (!$("#results li:first").hasClass("selected") && !started) {
$("#results li:first").addClass("selected");
started = true;
} else {
if($("#results li.selected").next().length > 0) {
$("#results li.selected").next().addClass("selected");
$("#results li.selected:first").removeClass("selected");
}
}
assign = $(".selected").text();
$(".autocomplete").val(assign);
break;
case 38:
$("#results li.selected").prev().addClass("selected");
$("#results li.selected:last").removeClass("selected");
if(!$("#results").siblings('.selected').length > 0) {
started = false;
}
assign = $(".selected").text();
$(".autocomplete").val(assign);
break;
case 13:
assign = $(".selected").text();
console.log(assign);
$("#results").empty();
$("#inner").text(assign);
break;
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "autocomplete.php?search=1",
success: function(data) {
$.each(data.client, function(key, value) {
username.push(value.username);
businessname.push(value.businessname);
fname.push(value.fname);
lname.push(value.lname);
clientid.push(value.clientid);
for(var i = 0; i < fname.length; i++) {
fullname[i] = fname[i] + " " + lname[i];
}
});
bankArray = [username, businessname, fullname, clientid];
console.log(bankArray);
}
});
$(".autocomplete").on("keyup change", function(e) {
console.log(e.keyCode);
if(e.keyCode != 38 && e.keyCode != 40) {
$("#results").empty();
}
currentSearchString = $(".autocomplete").val();
if(currentSearchString) {
//$("#results").css('border-top', '1px solid black');
for(var i = 0; i < bankArray.length; i++) {
for(var j = 0; j < bankArray[i].length; j++) {
focusedArrayElement = bankArray[i][j].toLowerCase();
usernames = bankArray[0];
businessnames = bankArray[2];
fullnames = bankArray[3];
if(focusedArrayElement.indexOf(currentSearchString.toLowerCase()) > -1) {
focused_businessname = bankArray[1][j];
focused_fullname = bankArray[2][j];
focused_clientid = bankArray[3][j];
postedData = focused_fullname + " -- " + focused_businessname;
if (!$(".clientid." + focused_clientid).length) {
$("#results").append("<li id='" + (j + 1) + "' class='clientid " + focused_clientid + "'>" + postedData + "</li>");
}
}
}
}
}
else {
$("#results").empty();
started = false;
}
});
});
The basic principle is that when the document readies, an ajax call pushes all of the JSON data into a multidimensional array with different categories of information. From here, a first for loop searches through each array in the bankArray, and the second searches through each element of the current array. If the current search string in the input field matches the focused element from the array, it appends that information to a div below.
I feel as if the code is inefficient in how it deals with the JSON data and checks through it. If anyone has any suggestions on how to optimize the code, that would be great.

javascript not compatible with IE

My script does not work properly with Internet Explorer. The problem is that the 'data' (JSON.stringify (data);) is not updated with the new values ​​after the script has been run once, it updates the div's with the same values as ​​the first time it was run. I am a newbie when it comes to js, have no idea how to solve this. Grateful for help!
function ful() {
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data) {
var imp = "";
var imps = new Array();
var set = new Array();
var div1, div2, div3, div4, tmp, hum, tid = "";
var temp = "";
var humi = "";
imp = JSON.stringify(data);
var values = imp.split(',');
var i = 0;
var y = 0;
for (var x = 0; x < values.length; x++) {
imps[y] += values[x];
i++;
if (i == 4) {
y++;
i = 0
}
}
for (var x = 0; x < imps.length; x++) {
div1 = "impid" + x;
div2 = "temp" + x;
div3 = "hum" + x;
div4 = "tid" + x;
set = imps[x].split('"');
tmp = set[9];
hum = set[13];
tid = set[17];
for (var y = 0; y < tmp.length; y++) {
temp += tmp[y];
if (y == 4) break;
}
for (var y = 0; y < hum.length; y++) {
humi += hum[y];
if (y == 4) break;
}
document.getElementById(div1).textContent = "ID : " + set[5];
document.getElementById(div2).textContent = "Temprature : " + temp + " °C";
document.getElementById(div3).textContent = "Humidity : " + humi + " %";
document.getElementById(div4).textContent = tid;
temp = "";
humi = "";
tmp = "";
tid = "";
hum = "";
}
}
});
setTimeout(ful, 6000)
}
$(ful);
Internet Explorer caches ajax requests.
A simple workaround is to simply add a timestamp to the end of your request, forcing IE to get a new one. Jquery does this automatically for you when specifying the cache parameter with false:
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
cache: false,
success: ...
For other options, check out this post:
https://devcentral.f5.com/blogs/us/fixing-internet-explorer-amp-ajax#.UcIVBZyiVSQ

Categories