jQuery fresh ALL rows from PHP loop - javascript

Im not sure what is happening here, but I can not update this DIV per every row using this code. This code loads a initial user list, and loads the rest (after first 3) to a DIV dropdown triggered by click event.
<? foreach ($res as $row) { ?>
<script>
function fetchIndexUsers() {
$(function () {});
$.ajax({
url: '/ajax/ajax_live_index_users.php',
method: 'GET',
cache: false,
dataType: 'JSON',
data: {
item_id: <?=intval($row["item_id"])?>
},
success: function (data) {
var html_to_append = '';
array = [];
results = [];
$.each(data, function (i, item) {
results[i] = data[i];
array[0] = item.total;
array[1] = item.calc;
let icon = item.user.match(/(^|\W)yes($|\W)/i) ? 'arrow_upward' : 'arrow_downward';
html_to_append += '<div style="display:inline;float:left"><span class="material-icons" style="vertical-align:top;width:16px;padding-right:30px;color:#c0c0c0">' + icon + '</span></div><div style="display:inline;float:left;padding-bottom:1px"><a class="tooltip-newusers" title="' + item.username + '" href="/user/?id=' + item.user_id + '"><img style="box-shadow:2px 2px 10px #D3D3D3;height:35px;width:35px;border-radius:50%;margin-bottom:6px;margin-right:-20px;margin-top:-5px;vertical-align:middle;position:relative;z-index:10005;border:2px solid #FFF" src="/' + item.avatar + '" /></a></div><div style="clear:both"></div>';
return i <= 3;
});
if (array[0] >= 3) {
$("#live-peers-more-<?=intval($row["item_id"])?>").html('<div id="slidedown-<?=intval($row["item_id"])?>" style="user-select:none;margin-top:-14px;position:absolute;right:-20px;font-size:13px;background:purple;padding:0 6px;text-align:center;border-radius:3px;color:#FFF;font-weight:500;text-decoration:none;text-shadow:0 1px 1px rgba(0,0,0,.3);box-shadow:2px 2px 10px #D3D3D3"><a style="color:#fff;cursor:pointer">+ ' + (array.length - array[1]) + (array[1] >= 2 ? ' peers' : ' peer') + '</a></div>')
if (array[1] === 0) {
$("#live-users-more-<?=intval($row["item_id"])?>").hide();
}
}
$("#live-users-<?=intval($row["item_id"])?>").html(html_to_append);
$('.tooltip-newusers').tooltipster({
animation: 'grow',
delay: 200,
interactive: true,
theme: 'tooltipster-punk'
});
$("#live-peers-<?=intval($row["item_id"])?>").css('background', 'none');
$("#slidedown-<?=intval($row["item_id"])?>").html('<span><a style="color:#fff;cursor:pointer">+ ' + array[0] + (array[0] >= 2 ? ' peers' : ' peer') + '</a></span>');
}
});
$("#live-users-more-<?=intval($row["item_id"])?>").click(function () {
$("#slidedown-<?=intval($row["item_id"])?>").css('z-index', '9999999');
$.ajax({
url: '/ajax/ajax_live_index_users.php',
method: 'GET',
cache: false,
dataType: 'JSON',
data: {
item_id: <?=intval($row["item_id"])?>,
more: 1
},
success: function (data) {
var html_to_append = '';
$.each(results, function (i, item) {
html_to_append += '<div id="more_users" style="padding:6px;text-shadow:0 1px 1px rgba(0,0,0,.3)"><div id="peer-username">' + truncateString(item.username, 6) + '</div><a class="tooltip-newusers" title="' + item.username + '" href="/user/?id=' + item.user_id + '"><img style="height:35px;width:35px;border-radius:50%;border:2px solid #FFF" src="/' + item.avatar + '" /></a><div style="font-size:11px;font-weight:normal">' + formatBytesSpeed(item.totalspeed) + '</div></div>';
$("#slidedown-<?=intval($row["item_id"])?>").css('height', 'auto');
});
$("#slidedown-<?=intval($row["item_id"])?>").html(html_to_append);
$('.tooltip-newusers').tooltipster({
animation: 'grow',
delay: 200,
interactive: true,
theme: 'tooltipster-punk'
});
}
});
});
}
fetchIndexUsers();
setInterval(function () {
fetchIndexUsers()
}, 5000);
</script>
<div id="live-users-<?=intval($row["item_id"])?>" style="padding:10px;background:url(/images/loading-ellipsis.svg) no-repeat left">
<span style="padding-right:89px"></span>
</div>
<div id="live-users-more-<?=intval($row["item_id"])?>"></div>
<? } ?>
But any action coming back only updates the last row in from the array (PHP foreach array, with the JS emedded in the loop picking up on the ID from the iteration).
How come it only interacts with the last row? How can I update all rows since I am using a unique ID?
Thank you

You need to move the script out from the loop completely. Have ONE version of the script that delegates like this
$("#container").on("click", ".live-users-more",function () {
const item_id = $(this).prev().attr("id"); ....
and then change
<div id="live-users-more-<?=intval($row["item_id"])?>"></div>
to
<div class="live-users-more"></div>
where you have a
<div id="container"></div>
that wraps all the live user divs

Related

Product Loop Problem in Javascript Categories

We made a category structure where products can be listed without changing the page. However, instead of stopping when the products in the category are exhausted, it first brings the products in the category, and then continues to pull products from another unrelated category. We couldn't find where we went wrong.
loadFsk('{{baseurl}}index.php?route=product/category&path='+selecteds.join('_'));
$.get('{{baseurl}}index.php?route=common/fskcats/search&catid=' + did, function (json) {
for (var i = (step); i < 6; i++) {
$('.seller-subcategories.step' + (i + 1)).remove();
}
if (step == 0) {
$('#catappends').html('');
}
if (json) {
var html = '<div class="seller-subcategories step' + (step + 1) + '"><ul class="seller-sub-ul">';
$(json['categorys']).each(function (k, v) {
html += '<li class="seller-sub-li"><a class="catjs" data-step="'
+ (step + 1) + '" data-id="' + v['category_id'] + '">' + v['name'] + '</a></li>'
});
html += '</ul></div>';
$('#catappends').append(html);
}
}, 'JSON');
});
function loadFsk(url,isnew=false){
$.ajax({
url: url,
dataType:'HTML',
success: function(htmlData){
if (isnew) {
$('.main-products-wrapper .main-products.product-grid').html($(htmlData).find('.product-grid .product-layout'));
}else{
$('.main-products-wrapper .main-products.product-grid').html($(htmlData).find('.main-products-wrapper .main-products.product-grid .product-layout'));
}
$('.pagination-results').html($(htmlData).find('.pagination-results'));
}
});
Journal.infiniteScrollInstance = $.ias({
container: '.main-products',
item: '.product-layout',
pagination: '.pagination-results',
next: '.pagination a.next'
});
}
window.addEventListener('load', () => {
let el = document.querySelector('.seller-horizontal .seller-ul .seller-li.active');
if(el){
let left_value = el.offsetLeft - (window.innerWidth/2) + (el.offsetWidth/2);
el.parentNode.scrollTo({
left: left_value,
behaviour: 'smooth',
});
}
})

Unable to set onclick in AJAX loaded table

Actually in my website i'm building a timeline from AJAX and i was trying to set the onclick on each table row.
I was using class selector but the effect was nothing.
I actually read in another stackoverflow post that i had to set onclick on the closest static item but nothing.
So i've tryed
$(".timeline").on("click","table-row",function () { alert("we") ;});
and
$(".table-row").click(function () { alert("we"); });
Actually AJAX code where i create the timeline is the following
function createTavoli(salaSelect) {
$.ajax({
type: "POST",
url: "Default.aspx/getTavoli",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
data = r.d;
data = $.parseJSON(data);
var count = 0;
var time = [];
$.each(data, function (i, item) {
var tabs = [];
var numtav = item.NUM_TAV;
var desctav = item.DESC_T;
var coperti = item.COPERTI;
var sala = item.SALA;
if (sala == salaSelect) {
tabs.push('<tr id="' + numtav + '" data-salatav="' + sala + '" class="table-row">');
if (desctav != "") {
tabs.push('<th scope="row" class="noselect row-head text-left">' + desctav + '<span class="badge badge-dark ml-1">' + coperti + '</span></th>');
} else {
tabs.push('<th scope="row" class="noselect row-head text-left">' + "T. " + numtav + '<span class="badge badge-dark ml-1">' + coperti + '</span></th>');
}
for (var i = 0; i <= 95 - Range; i++) {
tabs.push('<td style="padding: 0px; position: relative; z-index: 1;"></td>');
}
tabs.push('</tr>');
count++;
$('#timeline').append(tabs.join(""));
}
});
time.push('<th scope="col" style="padding: 0px; border: 0; width: 80px;" class="row-head"></th>');
for (var i = PartenzaOra; i <= 23; i++) {
time.push('<th style="padding: 0px; border: 0; z-index: 3;" scope="colgroup" colspan="4"><p class="h noselect">' + ('0' + i).slice(-2) + '</p></th>');
}
$('#timehead').append(time.join(""));
$('#counttav').text(count);
getTavoli(new Date());
},
error: function (xhr, status, errorThrow) {
alert(xhr.status + " " + xhr.responseText);
}
});
}
So which could be the best method to set onclick on the table-row class?
Here is JSFiddle of how's build the timeline
You should set click event after rows pushed to table. So put your $(".table-row").click(function () { alert("we"); }); code to end of success function.
Did you tried
$(document).on("click", ".timeline .table-row" , function() {
alert("we");
});
you can try this
$('body').on("click", ".table-row" , function() {
alert("we");
});

Display data received from drop box value

I would like once the user selects a different item in the drop box list which was taken from a mysql database, that specific data to that field be displayed.
Currently, I am able to get the value of the item in the drop down box but I am unable to use it.
<h3>Drop down Menu</h3>
<select id="dmenu">
<option selected="selected" id="opt">Choose your station</option>
</select>
<div id="optionT"></div>
$(document).ready(() => {
window.onload = ajaxCallback;
function ajaxCallback(data) {
var data;
var myOptions;
var output;
$.ajax({
url: 'http://localhost:5000/alldata',
type: 'GET',
datatype: 'json',
success: (data) => {
//$.each(data, function (index, value) {
var output = [];
$.each(data, function(key, value) {
output.push('<option value="' + key + '">' + value.Station +
'</option>');
});
$('#dmenu').html(output.join(''));
}
})
}
});
$('#dmenu').on('change', function() {
//alert( this.value );
//alert($(this).find(":selected").value());
function stationData(data) {
var stationName = $(this);
alert(stationName.val());
//var stationName = $(this).value();
//var stationName = $(this).find(":selected").value()
$.ajax({
url: 'http://localhost:5000/alldata',
method: 'POST',
data: {
station: stationName
},
success: (data) => {
$.each(data, function(i) {
data[i]
//console.log(i);
var station_loopOp = '';
//console.log(JSON.stringify(data[i].Station));
station_loopOp += '<li>ID: ' + JSON.stringify(data[i].ID) +
'</li>' +
'<li>Station: ' + JSON.stringify(data[i].Station) +
'</li>' + '<li>Address:
'+JSON.stringify(data[i].Address) +
'</li>' + '<li>' +
Sales: JSON.stringify(data[i].Monthly_CStore_Sales) +
'</li>' + '<li>Operator: ' +
JSON.stringify(data[i].Operator) + '</li>' +
'<li>Top SKU: ' + JSON.stringify(data[i].Top_SKU) +
'</li>' +
'</<li>' + '<br/>');
$('#optionT').html(station_loopOp);
}
});
}
});
You are just defining the function stationData(data){....} inside the callback function but not calling it anywhere inside of it .
Add this line into your function : stationData(<your-data>);

I have javascript code to view a news from RSS as a vertical list. I need help to move the list of topics as horizontal one by one, in one line

I have javascript code to view a news from RSS as a vertical list.
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 0,
TitleLinkTarget: "_blank",
DateFormat: "",
DateFormatLang:"en"
}, opt);
var id = $(this).attr("id"), i, s = "", dt;
$("#" + id).empty();
if (def.FeedUrl == undefined) return;
$("#" + id).append('<img src="loader.gif" />');
var YQLstr = 'SELECT channel.item FROM feednormalizer WHERE output="rss_2.0" AND url ="' + def.FeedUrl + '" LIMIT ' + def.MaxCount;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(YQLstr) + "&format=json&diagnostics=false&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
if (!(data.query.results.rss instanceof Array)) {
data.query.results.rss = [data.query.results.rss];
}
$.each(data.query.results.rss, function (e, itm) {
s += '<li><div class="itemTitle"><a href="' + itm.channel.item.link + '" target="' + def.TitleLinkTarget + '" >' + itm.channel.item.title + '</a></div>';
if (def.ShowPubDate){
dt = new Date(itm.channel.item.pubDate);
s += '<div class="itemDate">';
if ($.trim(def.DateFormat).length > 0) {
try {
moment.lang(def.DateFormatLang);
s += moment(dt).format(def.DateFormat);
}
catch (e){s += dt.toLocaleDateString();}
}
else {
s += dt.toLocaleDateString();
}
s += '</div>';
}
if (def.ShowDesc) {
s += '<div class="itemContent">';
if (def.DescCharacterLimit > 0 && itm.channel.item.description.length > def.DescCharacterLimit) {
s += itm.channel.item.description.substring(0, def.DescCharacterLimit) + '...';
}
else {
s += itm.channel.item.description;
}
s += '</div>';
}
});
$("#" + id).append('<ul class="feedEkList">' + s + '</ul>');
}
});
};
})(jQuery);
I need help to move the list of topics as horizontal one by one, in one line. by used javascript code. this code display just 5 topics, which I need it, but I have problem to how can I movement it as horizontal.

.empty() function won't work after loading contents with ajax

I did a multilevel ajax call .i.e. make an ajax call and use the id value from the call to make another call... I tried calling a jquery .empty() isn't working for the data generated in the inner ajax call... But when i place the .empty() function on the outer generated element, it worked just fine... How can i fix this issue? This is my code../
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({ //first ajax call///
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function(output) {
if (output.result === 'success') {
$('.blog').empty();
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var storyTitle = this.story_view;
var frontTitle = '<div class="blog-item"><h3>' + storyTitle + '</h3>' + '<img class="img-responsive img-story" src="images/blog/blog1.jpg" width="100%" alt="" />' + '<div class="blog-content"><div class="entry-meta"><h4>Episodes</h4></div>' + '<div class="well" style="padding-right: 10px; padding-left: 5px; width: 105%;">' + '<ul class="tag-cloud stories">';
var request2 = $.ajax({ ////inner ajax call//////
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function(output2) {
var i = 1;
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
var title = this.title;
var count = this.episode_count;
if (count == 0) {
frontTitle += id2;
} else if (i % 20 == 0) {
frontTitle += '<li data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li></ul><ul class="tag-cloud">';
} else {
frontTitle += '<li style="margin: 1px" data-id="' + id2 + '" id="singleEpisode"><a class="btn btn-sm btn-primary" href="#story/' + storyTitle + '/' + title + '">' + i + '</a></li>';
}
i += 1;
})
}
$('.blog').append(frontTitle);
frontTitle += '</ul></div></div>';
})
})
} else {
console.log('failed');
}
});
});
I really need help for this, i av been on this for two days now... I would really appreciate the help.. or is there a better way i could do this?

Categories