So I have this little loop which checks the id of the last div on my page and then replaces the div with a rendered updated div using ajax, then loops around and repeats. Now the problem I have is that if it loops and the id of the last div is the same it just adds another updated div so I get two of the same thing. I would only want it to append the data again if the id of the last div has changed (i.e it's a different div), but I don't think Javascript has an onChange method for calling the request only when id has changed. How might I go about this in JS?
Thanks in advance.
$( window ).load(function() {
update_live();
});
function update_live (){
var id = $(".tasktable").last().attr('id');
$.ajax({
type: 'GET',
url: "/ansible_jobs/update_live/",
data: { task_id: id },
dataType: 'html',
success: data_append
});}
function data_append(data){
$('.tasktable').last().empty();
$('.tasktable').last().replaceWith(data);
setTimeout(update_live, 2000);
}
Change update_live() to update_live(previousId), compare it with the current one, and update only if it is different. Pass the id forward.
Related
So basically, my chat right now works like this:
Every 2nd second it checks for my PHP file, loadchat.php.
Loadchat.php will get every row that is newer than their session.
It then replaces all current data in my div: #chatbox by using
.html() function.
Now here is the deal.
This seems very resource heavy, to load all the rows again and again and again.
I know there is a way to optimize this, by using .append() function.
All though, I can't seem to wrap my head around it.
I need to make some kind of a counter, or a timestamp when the last message was loaded to check if there is newer content (rows) than since last time it loaded, if there is, append that new content.
If I replace the .html function with .append, I will just keep getting the same messages over and over again, as right now.
How would I go about making this?
Thanks in advance.
//AJAX Timeout Loop Load Chat Function:
function loadChat() {
$.ajax({
method: 'POST',
url: 'ajax/load_chat.php',
success: function(data) {
$('#chatbox').html(data);
//console.log($('#chatbox')[0].scrollHeight - $('#chatbox').innerHeight());
//console.log($('#chatbox').scrollTop());
if(atBottom) {
$("#chatbox").stop().animate({ scrollTop: $('#chatbox')[0].scrollHeight}, 500);
}
},
});
}
EXAMPLE OF WHAT LOADCHAT WILL SEND BACK:
<script type="text/javascript">var imAdmin = true</script>
<div data-chat-sid="76561198216640736" data-chat-msid="76561198216640736" data-chat-sun="deinhoin" class="chat-box__content--single chat-box--mychat">
<div class="chat-box__content__single--avatar">
<div class="admin" style="background-image:url(https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/83/83b9e88c1f88451dcc97d2537416bbd413247ad6_full.jpg);"><span>Mod</span></div>
</div>
<div class="chat-box__content__single--title">deinhoin</div>
<div class="chat-box__content__single--message">adada</div>
</div>
It should only send the var imAdmin variable once. (works with .html()).
Try using .slice()
// `section` : container for chat message elements
var html = $("section div");
// `data` : `html` returned from server
var data = "<div>1</div><div>2</div><div>3</div>";
// if `data` `.length` greater than existing `section` `div` `.length`,
if ($(data).length > $(html).length) {
// `.slice()` elements greater than existing `section div` length
var newdata = $(data).slice($(html).length);
// append new elements to `section div`
$("section").append(newdata);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section>
<div>1</div><div>2</div>
</section>
Try making use of the 'data' attribute. You could have something like 'data-timestamp' on each chat item and use that to work out what was placed when.
I have a div that contains people's names, which is coming dynamically.
I want to show related content of people, when it's clicked. For that, I need to pass name of person to javascript when div is clicked.
How can I achieve this?
Note: I am not using any button.
for example:
$('#parent_block_that_not_insert_dynamicly').on('click', 'div.that_add_dynamycly', function() {
var data = $(this).text(); //get name
$.ajax({
method: "POST",
data: data,
url: "url.php"
})
.done(function(msg) {
alert('saved')
});
});
I am using the tooltipster plugin tool where I got gantt chart drawn with some td given id.
So, which ever id is defined and the mouse over it will get ajax data and show accordingly.
Below is snippet of my codes. Issue here is that the tool tip only appear after few times I mouse the td. Thereafter, it works fine.
I can see, in my debug window, that ajax page is called and following error:
Tooltipster: one or more tooltips are already attached to this element: ignoring. Use the "multiple" option to attach more tooltips. jquery.tooltipster.min.js:1
$(document).ready(function () {
$('td[id]').tooltipster({
// content: 'Loading...',
functionBefore: function(origin, continueTooltip) {
// We'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data
continueTooltip();
var idval=0;
// Next, we want to check if our data has already been cached
//if (origin.data('ajax') !== 'cached') {
$.ajax({
type: 'GET',
url: 'getDetails.php',
data:idval,
success: function(data) {
// Update our tooltip content with our returned data and cache it
//alert("Data is : "+data);
var finalData = 'Total Data : 300 <br> Total Completed : 200';
//alert("DATA");
//origin.tooltipster: $('<span>testst<strong>This text is in bold case !</strong></span>')
origin.tooltipster({
content: finalData,
multiple: true,
contentAsHTML: true
});
//origin.tooltipster({content: data,contentAsHTML: true}).data('ajax', 'cached');
}
});
//}
}
});
});
The Tooltipster plugin really should be initialised before all of this. Using the mouseenter enter to trigger it's initialisation every time a user hover's over a <td> element is not great practice and is the root problem to your issue. Ideally you would want to break it down into the following:
Find your <td> elements with id's defined.
Apply tooltipster to these elements.
Let tooltipster handle everything from there.
1. Finding your <td> elements
With the magic of jQuery you can fetch these with a clever use of selectors rather than querying a larger set with your initial implementation, gathered from the answers within the StackOverflow thread here, jquery get only all html elements with ids, we get:
$('td[id]')
This will fetch you all <td> elements with an id defined, be warned this could be a bit slow if you have an extensive table. Alternatively you can select, then apply a filter to narrow down your set:
$('td').filter(function(){
return $(this).attr('id') !== undefined;
});
Both will essentially do the same!
2. Applying tooltipster to these elements
I've not done much here since you had a lot of commented out code, so I've kept it the same, with some minor tweaks, here is my version of the "working code":
$('td[id]').tooltipster({
// content: 'Loading...',
functionBefore: function(origin, continueTooltip) {
// We'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data
continueTooltip();
// Next, we want to check if our data has already been cached
//if (origin.data('ajax') !== 'cached') {
$.ajax({
type: 'GET',
url: 'getDetails.php',
data: $(this).attr('id'),
success: function(data) {
// Update our tooltip content with our returned data and cache it
//alert("Data is : "+data);
var finalData = 'Total Data : 300 <br> Total Completed : 200';
//alert("DATA");
//origin.tooltipster: $('<span>testst<strong>This text is in bold case !</strong></span>')
origin.tooltipster({
content: finalData,
multiple: true,
contentAsHTML: true
});
//origin.tooltipster({content: data,contentAsHTML: true}).data('ajax', 'cached');
}
});
//}
}
});
3. Letting tooltipster handle everything from here
Tooltipster (when intialised) is triggered by default when hovering over an element, this means your functionBefore will be run before this "hover" event, causing your AJAX request to be run each time, there is no need to do anything more thereafter :D
I hope this helps! :)
You can use this code :
var tooltipInstance;
$("body").on('mouseover', 'td[id]:not(.tooltipstered)', function(){
tooltipInstance = $(this).tooltipster({
//your code ...
});
tooltipInstance.tooltipster('open');
});
I am writing a function to dynamically load jQuery UI accordian leaves with content. I know (think) the AJAX part works as I lifted it from another working AJAX loader I have, but the function as a whole does not work.
The code:
function load_leaf(link){
var link = link;
$.ajax({
cache : false,
type : 'POST',
async: false,
url : 'includes/'+ link +'.php?'+ new Date().getTime(),
dataType : 'text',
data: {
owner : '$user_id'
},
success: function(msg){
$("#" + link).html(msg);
console.log('Can\'t see me in Chrome, but ok in firefox !')
},
error: function() {
console.log($.makeArray(arguments));
},
complete: function() {
console.log($.makeArray(arguments));
}
});
};
$(function(){
$('.accordian').click(function(){
var link = this.getAttribute("link");
load_leaf(link);
});
});
For whatever reason this does not work. The break point seems to be this line
$("#" + link).html(msg);
Specifically the selector, as a hard coded selector works perfectly. The link variable is correctly filled i know this as i can alert the value correctly. The link is not the problem as i replaced the whole ajax function with a simple add class and it a still did not work, it also broke at the selector.
EDIT:
This is the div as printed by php:
<h3 class="accordian" id="'.$tab_id.'" link="'.$tab_link.'" >
'.$tab_name.'
</h3>
<div id="'.$tab_link.'"><p>Hi</p></div>
The html for the first one is:
<h3 class="accordian" id="accordian_manage.php" link="accordian_manage.php" >Manage Images</h3><div id="accordian_manage.php"><p>Hi</p></div>
Your ID has a period . in it, which jQuery interprets as a chained class selector.
You can either change your link/IDs, or use this hack:
$("[id='" + link + "']");
Live demo
I guess your problem is with Jquery is not finding the div to load the msg..Post the accordion div so that i could give you the proper selector
Hey All - I am having a bit of trouble with a jquery function. I have a nav bar and I want when a user clicks on the nav bar to have the page load into a div (#content)
The code I have works for the first click, but when I try to click on another item it shows the loading image, but does not put the new content in the div (it leaves the old content). Any thoughts?
$(document).ready(function() {
$('.cat').live("click",function() {
var section = $(this).attr("id");
$.ajax({
type: "POST",
url: "../soccer/nav/" + section + ".php",
beforeSend: function() {
$('div#content').hide();
$('div#loading').show();
},
success: function(html){
$('div#loading').hide();
$("div#content").replacewith(html);
}
});
return false;
});
});
Any help would be greatly appreciated!
The problem is the .replacewith() method. You are actually replacing the #content div with the new content. Just use .html() instead.
You don't need $("div#content"). You can just do $("#content")
$("#content") means find the node with the id "content".
Try with:
$.post("../soccer/nav/" + section + ".php", null, function(data)
{
$('#loading').hide();
$("#content").html(data);
});
Try to use jQuery.Load event to make use of ajax and html populating at the same time.