clearTimeout not working as expected when button is clicked again - javascript

I have 2 button, and when either buttons is clicked, the time is shown below. Both buttons have separate outputs. I'm trying to use clearTimeout, but it's not clearing the timeout for some reason. When a button is clicked again, it just makes another ajax call on top of the already existing ajax call. How do I get clearTimeout to work?
<input type = 'submit' value = 'show time' onclick = "showTime('test1.php', 'output1',0)">
<div id = 'output1'></div>
<input type = 'submit' value = 'show time' onclick = "showTime('test1.php', 'output2',1)">
<div id = 'output2'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
var timeout = [];
function showTime(gotoUrl,output,index) {
if (timeout[index]) {
clearTimeout(timeout[index]);
}
$.ajax({
type: "POST",
url: gotoUrl,
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
showTimeX(gotoUrl, output);
} //end of success:function(data)
}); //end of $.ajax
} //end of function showTime(gotoUrl, output)
function showTimeX(gotoUrl,output,index) {
$.ajax({
type: "POST",
url: gotoUrl,
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
timeout[index] = setTimeout(function(){showTimeX(gotoUrl, output, index)}, 5000);
} //end of success:function(data)
}); //end of $.ajax
} //end of function showTime(gotoUrl, output)
</script>

Your function showTime(gotoUrl,output,index) calls showTimeX(gotoUrl, output) on success.
But the showTimeX(gotoUrl,output,index) definition requires index as last argument, which is not specifed when you call that function.
Could it be that index is undefined and so timeout array doesn't contain any variables?

Related

Need to be able to run an ajax call with element loaded after document.ready()

I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});

Alerting string using document.getElementById().innerHTML

I'm trying to alert a string, using document.getElementById().innerHTML, but it's alerting the code of the whole page, instead of the string inside the div. I need it to alert '121'. What am I doing wrong?
<script type = "text/javascript">
function getUrban(pageNum, stopAt, gotoUrl) {
var currentPage = "currentPage";
$.ajax({
type: "POST",
url: gotoUrl,
data: { pageNum : pageNum },
error: function(xhr,status,error){alert("error");},
success:function(data) {
document.getElementById("output").innerHTML = data;
currentPage = document.getElementById("output").innerHTML;
},
complete:function(data) {
alert(currentPage);
} //end of complete:function(data)
});
} //end of function getUrban(pageNum)
getUrban(121,422,"test.php");
</script>
<div id = "output"></div>
Output in Alert:
The full code of the whole page, plus some more code about setting the width.
Output in div with id 'output':
121
Need Alert:
121
test.php
$pageNum = $_POST['pageNum'];
echo $pageNum;
Since you're using jQuery to do the ajax why don't you use jquery for everything else also.
$('#output').text();
Will get only the text inside the div. Not the html elements as well.
It drives me crazy to see people using jQuery and have document.getElementById('id') in their code. You do realize that $('id') will get the same element but with jQuery wrapper so you can use jQuery functions on it. And it's so much shorter to type.
<script type = "text/javascript">
function getUrban(pageNum, stopAt, gotoUrl) {
$.ajax({
type: "POST",
url: gotoUrl,
data: { pageNum : pageNum },
error: function(xhr,status,error){alert("error");},
success:function(data) {
$("#output").html(data);
},
complete:function(data) {
alert($('#output').text());
} //end of complete:function(data)
});
} //end of function getUrban(pageNum)
getUrban(121,422,"test.php");
</script>
<div id = "output"></div>

Repeat the function for every 1 min?

i am calling a function with parameters from onclick method what i want to do is i want this function to repeat every 1 min here is html code:
I am calling a function on everyclick with some parameter as id
The id fetches the the lat longs,and it is plotted in map ,i have done everything working except that i get the data keep recieving from the back end so what i want to do is , as i have clicked the href i want that particular id to be sent and keep recieve the data of that particular id only and when i click the second the first should be stopped and start the another .
<html>
</head>
<body>
</body>
</html>
javascript:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
Try this...
Use setInterval to call function every 1 minute and "trigger" function to click automatically when call function "test"
<html>
</head>
<body>
sdsd
sdsd
</body>
</html>
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
function test() {
$(".todo").trigger("click");
}
var refreshId = setInterval(test, 60000);
You can simply call a setInterval inside your todo function and it will fire with different calls, change your function like this:
function todo(id) {
setInterval(function() {
/*$.ajax({
type: "GET",
url: "example?value=" + id,
dataType: "text",
success: function(data) {
//parsing;
});*/
console.log(id);
}, 1000);
}
link1
link2
I used only 1000 milliseconds for test here, you only have to change it to 60000 to fit your needs, you can see the results in the console..
Note:
Keep in mind that for each click you will fire a new setInterval() so you have to disable click events after the first setInterval() to avoid this problem.
It is not clear as to what constraints you may require from your question and comments, but perhaps something like this?
Repeat will be stopped if there is an ajax error.
Clicking a button will cancel the current repeat and immediately start the new repeat (1-4). Requests in progress are not cancelled and there is no checking included to ignore processing them upon complete.
A stop button is included, this will stop the repeat but not the request in progress.
The requests are async and no effort has been made to make sure that they are processed in order of request.
This is a very basic example that starts you moving in the right direction.
var pre = document.getElementById('out'),
interval = 5,
running = false,
fetching = false,
timerId;
function stop() {
clearInterval(timerId);
running = false;
}
function todo(id) {
fetching = true;
$.ajax({
type: 'GET',
url: 'http://jsonplaceholder.typicode.com/albums?id=' + id,
dataType: 'jsonp',
error: function (qXHR, textStatus, errorThrown) {
pre.textContent += id + ': ' + textStatus + '\n';
stop();
},
success: function (data) {
pre.textContent += id + ': ' + data[0].title + '\n';
},
complete: function () {
fetching = false;
}
});
}
function start(id) {
if (running) {
stop();
}
running = true;
if (!fetching) {
todo(id);
}
timerId = setInterval(function () {
if (!fetching) {
todo(id);
}
}, interval * 1000);
}
document.body.addEventListener('click', function (evt) {
var target = evt.target;
if (target.classList.contains('album')) {
start(target.value);
}
}, false);
document.getElementById('stop').addEventListener('click', function () {
stop();
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="album" value="1">1</button>
<button class="album" value="2">2</button>
<button class="album" value="3">3</button>
<button class="album" value="4">4</button>
<button id="stop">stop</button>
<pre id="out"></pre>
You can use setTimeout of javascript.
It will repeat given function in specified time interval.
Javascript setTimeout function repeat
OR
setInterval( function(){ todo(id);}, 60000);
Make use of setTimeout to call the function again:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
setTimeout(function(){todo(id)}, 60000);
}
And if you also want to clear timeout on some condition:
var timer;
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
timer = setTimeout(function(){todo(id)}, 60000);
if(//Your condition){
window.clearTimeout(timer);
}
}

I don't understand AJAX callbacks

I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});

JS/AJAX Auto submit form: Disabling enter key to prevent page refresh

I am using a function that will submit with ajax and without the help of a button click. But I am currently undergoing two issues which with trial and error haven't found plausible solutions:
First is there any way I can disable the enter button click(this causes the whole page to refresh)?
JSFIDDLE basic example in how the JS function works
Second, It feels like I am going the roundabout way to display what has been posted. How can I change this part of the function $('#special').html('<p>' + $('#resultval', result).html() + '</p>'); to have it POST just inside a div called #special without the need of span or <p> #resultval?
Everytime i echo through php I have to do set it like this to display a result: <div id="special"><span id="resultval">This is the result.</span></div>
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});
</script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(event){// the function call on click or on submit onclick=submitForm(event);
event.preventDefault(); //to prevent enter key
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').text(result); //you can use text() or html() only
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});

Categories

Resources