Click on table causes multiple ajax operations are running with jQuery - javascript

after looking for a solution of a problem I may found the turning point and can define the problem.
My code uses jQuery and Ajax and is triggered on a click on a table cell. The output was and is a table which I refresh within an interval.
Well, when I clicked on a cell and then on another cell the output is switching between the outputs based on the transmitted value of cell A and cell B.
I took a look into firebug and, voila, got a sneak on the reason.
GET http://localhost/trading/getuser_exp.php?q=NYSE
GET http://localhost/trading/getuser_exp.php?q=NASDAQ
Both values are running parallel and this is wrong. I need a single value or, in other words, if I clicked on NYSE before, value is NYSE, then I click on NASDAQ, the value isn't NYSE anymore, but NASDAQ.
The code is use is
$(document).ready(function(){
$(".information").click(function () {
var str = $(this).closest("tr").find("#nr").text();
window.setInterval(function(){
$.get("getuser_exp.php",
{ q:str },
function(data) { $('.stock').html(data);
} //function data
);
}, 3000);
}); //information click
}); //document ready
Now what causes the multiple firing? In my eyes - frank speaking a beginner - nothing is multiple firing or that is accepting multiple values. Whatever it is, I will learn.
Thank you for any assistance and help.

You need to clear the old interval and start a new one. This is why you get multiple firings as each click starts a new interval timer.
$(document).ready(function(){
var timer = null;
$(".information").click(function () {
var str = $(this).closest("tr").find("#nr").text();
if(timer!=null) {
clearInterval(timer);
}
timer = window.setInterval(function(){
$.get("getuser_exp.php",
{ q:str },
function(data) {
$('.stock').html(data);
}
);
}, 3000);
});
});

Related

Use jQuery to determine when Django's filter_horizontal changes and then get the new data

I have a filter_horizontal selector in my Django admin that has a list of categories for products (this is on a product page in the admin). I want to change how the product change form looks based on the category or categories that are chosen in the filter_horizontal box.
I want to call a function every time a category is moved from the from or to section of the filter_horizontal.
What I have now is:
(function($){
$(document).ready(function(){
function toggleAttributeSection(choices) {
$.getJSON('/ajax/category-type/', { id: choices}, function (data, jqXHR) {
// check the data and make changes according to the choices
});
}
// The id in the assignment below is correct, but maybe I need to add option[]??
var $category = $('#id_category_to');
$category.change(function(){
toggleAttributeSection($(this).val());
});
});
})(django.jQuery);
The function never gets called when I move categories from the left side to the right side, or vice versa, of the filter_horizontal.
I assume that $category.change() is not correct, but I don't know what other events might be triggered when the filter_horizontal is changed. Also, I know there are multiple options inside of the select box. I haven't gotten that far yet, but how do I ensure all of them are passed to the function?
If anyone can point me in the right direction I would be very grateful. Thank!
You need to extend the SelectBox.redisplay function in a scope like so:
(function() {
var oldRedisplay = SelectBox.redisplay;
SelectBox.redisplay = function(id) {
oldRedisplay.call(this, id);
// do something
};
})();
Make sure to apply this after SelectBox has been initialized on the page and every time a select box refreshes (option moves, filter is added, etc.) your new function will be called.
(Code courtesy of Cork on #jquery)
I finally figured this out. Here is how it is done if anyone stumbles on this question. You need to listen for change events on both the _from and _to fields in the Django filter_horizontal and use a timeout to allow the Django javascript to finish running before you pull the contents of the _from or _to fields. Here is the code that worked for me:
var $category = $('#id_category_to');
$category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
var $avail_category = $('#id_category_from');
$avail_category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
And this is how I get the contents of the _to field:
function getFilterCategoryIds() {
var x = document.getElementById("id_category_to");
var counti;
var ids = [];
for (counti = 0; counti < x.length; counti++) {
ids.push(x.options[counti].value);
}
return ids;
}
I know it was a convoluted question and answer and people won't come across this often but hopefully it helps someone out.

Javascript How to check if a call is being made, and kill it if it is

Using jQuery I'm writing a website api call in Javascript, which so far works pretty well. When a person updates a number in a text input it does a call to the API and updates a field with the response. It gets problematic however, when I user quickly makes a lot of changes. The javascript then seems to pile up all queries, and somehow does them side by side, which gives the field to be updated kind of a stressy look.
I think one way of giving the user a more relaxed interface, is to only start the API call after the user finished editing the input field for more than half a second ago. I can of course set a timeout, but after the timeout I need to check if there is not already a call under way. If there is, it would need to be stopped/killed/disregarded, and then simply start the new call.
First of all, does this seem like a logical way of doing it? Next, how do I check if a call is underway? And lastly, how do I stop/kill/disregard the call that is busy?
All tips are welcome!
[EDIT]
As requested, here some of the code I already have:
function updateSellAmount() {
$("#sellAmount").addClass('loadgif');
fieldToBeUpdated = 'sellAmount';
var buyAmount = $("#buyAmount").val();
var sellCurrency = $("#sellCurrency").val();
var buyCurrency = $("#buyCurrency").val();
var quoteURL = "/api/getQuote/?sellCurrency="+sellCurrency
+"&buyAmount="+buyAmount
+"&buyCurrency="+buyCurrency;
$.get(quoteURL, function(data, textStatus, jqXHR){
if (textStatus == "success") {
$("#sellAmount").val(data);
$("#sellAmount").removeClass('loadgif');
}
});
if (fieldToBeUpdated == 'sellAmount') {
setTimeout(updatesellAmount, 10000);
}
}
$("#buyAmount").on("change keyup paste", function(){
updateSellAmount();
});
If you make your AJAX call like this:
var myAjaxDeferred = $.ajax("....");
You can check it later with:
if (myAjaxDeferred.state() === "pending") {
// this call is still working...
}

Jquery load content then refresh every 2 second

i am having trouble solving this, i'm trying to load a page which process a variable given by an input form then show the content based on the input, this worked fine, but i am also trying to refresh and update that input every 2 seconds
Below are my codes
<script>
$(document).ready(function(){
function getData(){
$("#dateslot").change(function(){
var inputField= $('#dateslot').val();
$("#timeslot").load('burgerorder_check.php?dateselect='+inputField);
});
setTimeout(getData,1000);
};
getData();
});
</script>
I'm trying to create a function that if someone else picked that, you won't be able to, which i successfully coded but not for the refresh part.
You have the methods and variables in the wrong order. You should probably set a variable outside the getData scope that can change at anytime, then just use that variable when fetching data.
Also, use setInterval if you want to repeat the function. setTimeout is simply a delay.
var val; // the select value is stored here
$("#dateslot").change(function(){
val = $(this).val(); // change the value
}
setInterval(getData,1000);
getData();
function getData(){
if ( val ) {
$("#timeslot").load('burgerorder_check.php?dateselect='+val);
}
}

Javascript Refresh

Is there a way using the code below to instead of refreshing the time refresh a div id that is already there?
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('drawaddrow').innerHTML = ????;
}
</script>
Say I fi were to replace the time id with the the id that I wanted to refresh what would I put after .innerHTML =???
This is the div I need refreshed every second.
<div id="draw" align="center">
<table>
<tr><td style="height:20px;"></td></tr>
</table>
<TABLE style="float:center;border:5px; border-style:outset;border-color:#E80000; width:850px; border-spacing:0; border-collapes:collapse;" table border="1">
<div id="addrow"><script type="text/javascript">
Draw ("")
[Add]</script></div>
</table>
</div>
The [AddItemsHTML] somehow pulls data from a piece of software telling you what is due and what is not, however the script is not pulling the time every second the browser when refreshed just changed the time on the due status column.
Right now i'm using this to refresh the whole page I just need the drawaddrow div id refreshed.
function refreshPage () {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function () {
setTimeout(refreshPage, 1000);
if (window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
document.getElementsByTagName("body")[0].scrollTop = match[1];
}
Updated (on 27/07/2013 #08:20 AM IST):
Having gone through your code, the below is my updated answer.
Plainly assigning a value to the DIV (divaddrow) using (.innerHTML) wouldn't work due to the following reasons:
(a) The DIV has some code enclosed within square braces (like [AddItemsHTML]). I am not sure what technology it uses. But judging by its intended use (which is, to populate the table with data) it sure seems to require a communication with the server to fetch data.
(b) The DIV also has a <script> tag with a call to a function (lets call it cntFn). Plainly assigning the value would not work because value setting wouldn't call/execute the function again (like it does on page load).
Assuming point 1.a is wrong, the normal way to handle 1.b would be to first assign the static contents of the div using .innerHTML and then do either (a) write whatever the "cntFn" does into the function that is refreshing the page (lets call it refreshFn) also (or) (b) call the "cntFn" within the "refreshFn". The latter would also cause a problem here because the "cntFn" has a lot of document.write lines which would repaint the entire page (meaning the other contents of the page would be lost on executing the refresh).
Generally using document.write lines is a bad practice because they repaint the page fully. You can find more about this here.
The best alternate in my opinion would be to use AJAX to refresh the contents. The content of your divaddrow div would form the contents of the AJAX file that needs to be called every 'x' seconds. Be careful with the 'x' seconds part. Do not try to refresh the section every second because realistically it would take time for the AJAX request to reach the server and get the response. Set the refresh interval such that the first request would have been processed by the time the next one comes (at-least 90% of the cases). The amount of data (no. of rows) that the AJAX call would be fetching will also be a factor.
Check this out... I used Jquery for the same
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$('#show').text(
'I am getting refreshed every 3 seconds..! Random Number ==> '
+ randomnumber);
}, 3000);
});
WORKING FIDDLE
I'm not sure that I understand you, but is this want you mean?
function startTime()
{
document.getElementById('time').innerHTML = document.getElementById('target').innerHTML;
}
This is what I use:
<span>This page will refresh in </span><span id="countdown">60</span>seconds…
<script type="text/javascript">
setInterval(
function() {
if (document.getElementById('countdown').innerHTML != 0) {
document.getElementById('countdown').innerHTML--;
} else {
window.location = window.location;
}
}, 1000);</script>
If I've understood your question correctly, you can do something like this:
window.onload = function () {
function startTime () {
document.getElementById('date').innerHTML = new Date();
}
setInterval(startTime, 1000);
}
HTML:
<div id="time">This a div containing time: <span id="date"></span></div>
This is a JavaScript snippet, based on the original post, that counts the number of seconds since the page has loaded, assuming that there's an element with ID "time" and contents that are entirely numeric.
If the time remaining is given in seconds on the page you're working with, then it would be easy to adjust this accordingly. If the time remaining is not given in seconds, I'd need to see what the text in question actually looks like.
window.onload = startInterval;
var firstTime;
var valAtPageLoad;
function startInterval()
{
firstTime = new Date();
valAtPageLoad = parseInt(document.getElementById('time').innerHTML);
setInterval("startTime();",1000);
}
function startTime()
{
var timeDiff = (new Date() - firstTime)/1000;
document.getElementById('time').innerHTML = Math.round(timeDiff + valAtPageLoad);
}
If you want to reload your DIV and not the entire page, you would have to create the contents of that DIV on the server-side, and then use AJAX to load the DIV´s content. The easiest way to do this, is with jQuery:
function startTime() {
$.get('path/to/div/contents.html', function(data) {
$('#drawaddrow').html(data);
});
}

jQuery animation if load() returns something different

setInterval(function() {
var prevTopArticle = $("#toparticles table:first").html();
$("#toparticles").load("myurloffeed.com/topfeed", function()
{
alternateBG();
var newTopArticle = $("#toparticles table:first").html();
if (prevTopArticle!=newTopArticle)
{
$("#toparticles table:first").effect("highlight", {color:"#faffc4"}, 2000);
}
});
}, 8000);
So it sets the current first table item to a variable, loads the toparticles div with the tables off the url, and if they are different it will perform the highlight effect, however it does the highlight effect anyway, completely unsure why it isn't working.
For some reason one of the articles was outputting a twitter link and the other wasn't, thought the feeds were the same. Figured it out using console.log of the two variables.

Categories