jQuery clearinterval / stopinterval doesn't work - javascript

I have an autorefresh function that gets called if a checkbox is checked and a button clicked. I want to stop the autorefresh when the checkbox is unclicked:
var refreshId = null;
$("#disINFRAlive").click(function(infralivefun) {
event.preventDefault(infralivefun);
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
if ($('#autorefcheck').is(':checked')) {
var refreshId = setInterval(function() {
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
}, 5000);
}
});
The autorefresh works if the checkbox #autorefcheck is checked and the button #disINFRAlive is clicked. However, I can't make it stop by unchecking the checkbox:
function stopinterval(){
clearInterval(refreshId);
return false;
}
$('#autorefcheck').click(function() {
stopinterval();
});
I tried to use clearInterval in various ways and none worked so far.

Remove the var keyword from the initialization of refreshId.
if ($('#autorefcheck').is(':checked')) {
refreshId = setInterval(function() {
The way you have it, you are redeclaring the variable in a different scope. That way, you cannot access it from stopInterval().

Related

Change label text on mouse over with ajax

I want to change the value of a label on mouse over. This is what I have done so far:
$(function () {
var hoverOff = "";
$("[id*=GV] td").hover(function () {
hoverOff = $("label", $(this).closest("td")).text();
$.ajax({
type: "POST",
url: "MyMethode.aspx/GetNewValue?text=" + hoverOff,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("label", $(this).closest("td")).html(data.d);
}
});
},
function () {
$("label", $(this).closest("td")).html(hoverOff);
}
);});
At the beginning I save the current text in hoverOff and send that value to the method GetNewValue wich returns the new value and inside ajax success I want to apply that value to the label. The problem is that the text for label never changes, although data.d contains the new text. Should I use something else instead of .html()?
this inside ajax callback isn't referring to the current hovered TD but to the jqXHR object. You can use $.ajax context option:
context: this,
BTW, $(this).closest("td") is quite unrelevant because obviously, even you have nested TDs, $(this).closest("td") will always return the current TD, so you could just use this:
hoverOff = $("label", this).text();
And data: "{}", could be data: {},, no point of setting a string here. >> because you are setting contentype to JSON
It's a context problem you can't use this inside success function, try this code:
$(function () {
var hoverOff = "";
$("[id*=GV] td").hover(function () {
var label = $("label", $(this).closest("td"));
hoverOff = label.text();
$.ajax({
type: "POST",
url: "MyMethode.aspx/GetNewValue?text=" + hoverOff,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
label.html(data.d);
}
});
},
function () {
label.html(hoverOff);
}
);});
You could use this solution from https://stackoverflow.com/a/10701170/3421811
$('.btn').hover(
function() {
var $this = $(this); // caching $(this)
$this.data('initialText', $this.text());
$this.text("I'm replaced!");
},
function() {
var $this = $(this); // caching $(this)
$this.text($this.data('initialText'));
}
);

How to stop setInterval in a do while loop in jquery

I want to do is stop setInterval after the do while loop meet the condition.
My problem is even the while loop condition is meet the setInterval is still running.
do
{
setInterval(
Vinformation();
,500);
}while($('#emailCodeResult').val() !='')
function Vinformation(){
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
}
});
return false;
}
You don't need while loop here at all. In combination with setInterval it doesn't make sense. What you need is probably just setInterval:
var interval = setInterval(Vinformation, 500);
function Vinformation() {
if ($('#emailCodeResult').val() == '') {
clearInterval(interval);
return;
}
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType: "JSON",
success: function (result) {
}
});
}
Use clearInterval function to stop interval.
Also note, that setInterval expects function reference as the first argument so this setInterval(Vinformation(), 500) is not correct, because you immediately invoke the Vinformation function.
var itvl1= window.setInterval(function(){
Vinformation();
},500);
function Vinformation(){
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
if(data.emailCodeResult !=''){
window.clearInterval(itvl1);
};
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType:"Jenter code hereSON",
success: function (result) {
}
});
return false;
}

Issue with newElements function

I have a vote function in one of my projects. Please see following code.
$(function () {
$(".vote").click(function () {
var id = $(this).data("id");
var name = $(this).data("name");
var dataString = 'id=' + id;
//var dataId = id;
var parent = $(this);
if (name == 'up') {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_up.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
} else {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_down.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
}
return false;
});
});
and I'm using jQuery infinite scroll to load rest of the pages/posts. I'm using following code in main page and second page which i load rest of the data
('#left').infinitescroll({
navSelector: '#page-nav', // selector for the paged navigation
nextSelector: '#page-nav a', // selector for the NEXT link (to page 2)
itemSelector: '.post-box', //
}, function (newElements, data, url) {
$(".vote").click(function () {
var id = $(this).data("id");
var name = $(this).data("name");
var dataString = 'id=' + id;
//var dataId = id;
var parent = $(this);
if (name == 'up') {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_up.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
} else {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_down.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
}
return false;
});
});
Issue is after 2nd 3rd or any other page load, vote function is triggering twice. How can I fix this issue. Any help will be appreciated.
Maybe if you unbind the click event and then bind it
function(newElements, data, url){
$(".vote").unbind( "click" );
$(".vote").click(function() {
You need to unbind the click event before binding it again.
[...]
$(".vote").unbind('click').click(function()
[...]
or
[...]
$(".vote").off('click').click(function()
[..]
depending on the version of jQuery you are using.

Why trigger and click do not work in this case?

I have a piece of code that does:
$('td.unique').live('click', function () {
//function logic here
});
This works fine on I click on the td of my table. All fine!
Now I would like to be able to have the same functionality programatically in certain cases without the user actually pressing click.
I have tried:
$(document).ready(function() {
$(".clearButton").click( function () {
var username = $(this).closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $(this).closest('tr').find('label').val();
var input = [];
input[0] = {action:'reset', id:user_id,user:username,};
$.ajax({
url: 'updateprofile.html',
data:{'user_options':JSON.stringify(input)},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
//all ok
console.log("ALL OK");
$(this).closest('tr').find('.unique').trigger('click');
$(this).closest('tr').find('td.unique').trigger('click');
$(this).closest('tr').find('td.unique').click();
}
else {
alert('failed');
}
}
});
This button is in the same row that the td.unique is
None of these work. Why? Am I doing it wrong? Is the function that I have bind in live not taken into account when I click this way?
You need to cache the $(this) inside the ajax function.
var $this = $(this);
the $(this) inside the ajax function will not refer to the element that is clicked
$(".clearButton").click(function () {
var $this = $(this);
var username = $this.closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $this.closest('tr').find('label').val();
var input = [];
input[0] = {
action: 'reset',
id: user_id,
user: username,
};
$.ajax({
url: 'updateprofile.html',
data: {
'user_options': JSON.stringify(input)
},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
console.log("ALL OK");
$this.closest('tr').find('.unique').trigger('click');
$this.closest('tr').find('td.unique').trigger('click');
$this.closest('tr').find('td.unique').click();
} else {
alert('failed');
}
}
});
});

How Can I Do to my textbox autocomplete, works

I'm trying to do an autocomplete to my textbox, but it doesn't work. Follow my code.
$(function () {
var credenciada = '<%= credenciadaId %>';
xml_NomeCompleto = "";
var Nomes = "";
var retorno = '';
var count = 0;
var t = '';
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
t = $(this).find("NOMECOMPLETOUSUARIO").text();
Nomes += ["\"" + t + "\","];
});
}
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
});
The variable 't' receives all the names of my users, normally, but the autocomplete don't work.
Wait for ajax response to complete and then initialize the autocomplete because before you initialize the plugin data is not available. Also the way you are creating Nomes(source) is wrong. Declare it as an array and use push method to populate it.
Try this
var Nomes = [];
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
Nomes.push($(this).find("NOMECOMPLETOUSUARIO").text());
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
}
});

Categories

Resources