I have a button, where when you click it, it will show the time, wait 5 seconds, show the time again, and then repeats indefinitely. However, if you click the button again, it'll call the function again, so now there are 2 of the ajax calls running at the same time. So instead of waiting 5 seconds and showing the time, since there are 2 of the ajax calls running at the same time. So depending on when you clicked the button on the second time, it may wait for 2 seconds, show the time, wait for 3 seconds, show the time, repeats indefinitely.
I thought of making the button unclickable once it was clicked, but I can't do that because I plan to add to the button other functions other than the ajax setTimeout callback, and that won't work out if I make the button unclickable. So, my question is, is there a way to cancel the first ajax call before calling the second ajax call, somehow?
test1.php
<style>
#output {
width: 25%;
height: 25%;
border: 1px solid black;
}
</style>
<input type = 'submit' value = 'show time' onclick = "showTime('test2.php', 'output')">
<div id = 'output'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function showTime(gotoUrl,output) {
$.ajax({
type: "POST",
url: gotoUrl,
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
setTimeout(function(){showTime(gotoUrl, output)}, 5000);
} //end of success:function(data)
}); //end of $.ajax
} //end of function ajaxFunc(gotoUrl, output)
</script>
test2.php
<?php
date_default_timezone_set('America/New_York');
$time = date('H:i:s');
echo $time;
?>
This took more than a few edits, but i'm kind of rushing. It should be along these lines:
var $element = $('selector');
//add event handler on click
$element.click(function () {
//set up indefinite ajax call
setInterval(function (){
$.ajax({
url: url,
data: somedata,
method: 'get'
}).done(function (data) {
//do something
});
}, 5000);
//now we can remove the click event from the button
$element.off('click');
});
//now we can add new ones using the reference
$element.on(//do whatever you want);
If you store the response from setTimeout() in a variable you can cancel it next time the button is clicks with the clearTimeout() method.
clearTimeout(myShowTime);
myShowTime = setTimeout(function(){showTime(gotoUrl, output)}, 5000);
You can use xhr.abort(); method to abort the ajax call like this:
var xhr;
function showTime(gotoUrl, output) {
if (xhr) {
xhr.abort();
}
xhr = $.ajax({
type: "POST",
url: gotoUrl,
error: function (xhr, status, error) {
alert(error);
},
success:function (data) {
document.getElementById( output ).innerHTML = data;
setTimeout(function() {
showTime(gotoUrl, output)
}, 5000);
}
});
}
use jQuery .off() to unbind one handler:
http://api.jquery.com/off/
Related
I have created an Interval that runs on every 2 seconds, when the page loads. Now, when I move to other page, the interval is cleared (Please check the code). Now what I want is when I move to the same tab again, the interval should start again.
One thing I tried was that I wrote this whole code inside $(window).focus(//CODE) but the problem is that it doesn't run when the page is initially opened in any browser's tab.
How can solve this issue?
Here's my code:
var zzz= setInterval(anewFunc, 2000);
function anewFunc(){
$(document).ready(function(){
var chatattr=$(".chatwindow").css("visibility");
var chattitle=$("#hideid").text();
if(chatattr=="visible"){
$.ajax({
url: 'seen1.php',
type: 'post',
data: "ctitle="+chattitle,
success: function(result9){
},
error: function(){
}
});
}
$(window).blur(function(){
$.ajax({
url: 'session.php',
type: 'post',
success: function(result10){
// alert(result10);
},
error: function(){
}
});
clearInterval(zzz);
});
});
}
One thing I tried was that I wrote this whole code inside $(window).focus(//CODE) but the problem is that it doesn't run when the page is initially opened in any browser's tab.
Okay, the problem here is, the setInterval() doesn't execute at 0 seconds. It starts from 2 seconds only. So you need to make a small change:
Have the function separately.
Inside the ready event, start the timer, as well as run the function for the first time.
Remove the event handlers from the interval, or use just .one() to assign only once. You are repeatedly adding to the .blur() event of window.
Corrected Code:
function anewFunc() {
var chatattr = $(".chatwindow").css("visibility");
var chattitle = $("#hideid").text();
if (chatattr == "visible") {
$.ajax({
url: 'seen1.php',
type: 'post',
data: "ctitle=" + chattitle,
success: function(result9) {},
error: function() {}
});
}
$(window).one("blur", function() {
$.ajax({
url: 'session.php',
type: 'post',
success: function(result10) {
// alert(result10);
},
error: function() {}
});
clearInterval(zzz);
});
}
$(document).ready(function() {
var zzz = setInterval(anewFunc, 2000);
anewFunc();
});
Now what I want is when I move to the same tab again, the interval should start again.
You haven't started the setInterval() again.
$(document).ready(function () {
$(window).one("focus", function() {
var zzz = setInterval(anewFunc, 2000);
});
});
I am working on a dynamic online form website. In the main form, I have multiple sub-forms which can be added and deleted dynamically.
<div class='subform'>
//form fields
<input ...>
...
<button class='subform_submit'>
</div>
For each subform, I bind an AJAX call on the subform's submit button like this:
$('#main').on('click', '.subform_submit', function(){
// Get this subform's user input
...
$.ajax({
url: ..,
type: ..,
data: /* this subform's data */
});
});
So in that page, I may have 0 to 10 subforms depending on the user's selection.
I also have a main submit button on the bottom of the page, which can submit those subforms and the main form's data together.
$('#main').on('click', '#submit', function(e){
$('.subform_submit').click(); // Submit each subform
bootbox.confirm({ });
})
Once main submit button is clicked, I want to show a loading picture and then show a dialog box (I use bootbox.confirm() here) until all AJAX calls have completed.
This dialog box is telling user that whole form including sub-forms has been submitted.
But the problem is that each AJAX call may take 2 seconds to complete and I don't know how may calls may be pending completion. How can I write this main submit button so that it will:
Show the loading image immediately, and
Hide the loading image and show the dialog box after all AJAX calls have completed?
Keep track of how many sub-forms there are;
$subFormsCount = $('.subform').length;
Keep track of how many forms have been submitted;
$submittedForms = 0;
Each time a form finishes submitting, add to the $submittedForms;
$.ajax({
..
..
done: function(){
$submittedForms++;
}
})
Create a global timer to see if the number of submitted forms matches the total number of subforms. If true, hide the dialog box;
setInterval(function(){
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}, 50ms)
Edit
You could skip the global timer (as this will probably be a few milliseconds out) - include the check in your ajax.done instead;
$.ajax({
..
..
done: function(){
$submittedForms++;
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}
})
You want to use .done() in order to specify code that should wait until the AJAX asynchronous function completes.
$.ajax({
url:..,
type: ..,
data: /* this subform's data*/ })
.done(function() {
//Put code here
});
Have you tried .ajaxStop() event handler ?
$(document).ajaxStop(function() {
// place code to be executed on completion of last outstanding ajax call here
});
also, check this answer
I assume you have 9 subform and 1 main form.
Code for 8 subform will be same.
I use here async:false : Means next ajax will not be call until 1st one is not completed.
Sample Code Format :
var id = 5;
$.ajax({
url: ,
type: 'POST',
data: {'id':id},
dataType: 'JSON',
async: false,
error : function(xhr, textStatus, errorThrown) {
alert('An error occurred!');
},
success : function(response){
}
});
Just set variable in your last sub form that is 9th subform.
success : function(response){
var counter = true;
}
if(counter){
/* Code to show dialog.*/
}
You can use $.when to wait for each request to complete. Something like this should get you close. You'd basically want to store all the ajax requests in an array and pass that to when as the arguments.
$('#main').on('click', '.subform_submit', function () {
var formRequests = $('.subform').map(function () {
var $form = $(this);
return $.ajax({
url: '',
data: $form.serialzeArray()
});
}).get();
$.when.apply(undefined, formRequests).done(function () {
console.log('All done!');
});
});
Here goes a very similar little demo I just made up: https://jsfiddle.net/g9a06y4t/
I currently have the below function which updates the data in a div when the page is refreshed and this works fine however i want to edit the function to make it constantly update say every 2 seconds without having to refresh the page. How would i go about doing this?
<script>
$(document).ready(function ajaxLoop() {
//-----------------------------------------------------------------------
// Send a http request with AJAX Jquery
//-----------------------------------------------------------------------
$.ajax({
url: 'getOrderStatus.php', // Url of Php file to run sql
data: "",
dataType: 'json', //data format
success: function ajaxLoop(data) //on reciept of reply
{
var OrdersSubmitted = data[0].SUBMITTED; //get Orders Submitted Count
var OrdersFulfilled = data[0].FULFILLED; //get Orders Fulfilled count
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#OrdersSubmitted').html("SUBMITTED:" + OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:" + OrdersFulfilled); //Set output html divs
}
});
});
</script>
You can chain setTimeout calls to achieve this:
$(document).ready(function() {
function updateOrders() {
$.ajax({
url: 'getOrderStatus.php',
dataType: 'json',
success: function ajaxLoop(data) {
var OrdersSubmitted = data[0].SUBMITTED;
var OrdersFulfilled = data[0].FULFILLED;
$('#OrdersSubmitted').html("SUBMITTED:"+ OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:"+ OrdersFulfilled);
setTimeout(updateOrders, 2000);
}
});
});
The alternative is setInterval(), however if the requests slow down this can lead to calls being queued, which will eventually lead to memory issues.
You need to add a repeating event to call your updateOrders function. Like:
function startUpdateOrdersTimes() {
setInterval(function() {
updateOrders();
}, 2000);
//Call now (otherwise waits for first call)
updateOrders();
}
Using "window.setInterval" (https://developer.mozilla.org/en/docs/Web/API/window.setInterval) you can repeatedly execute a function at a specified time interval.
function SomeFunction()
{
$.ajax({...});
}
window.setInterval(SomeFunction,2000);
This would execute SomeFunction every 2 seconds
Hope this helps
timerupdateorders = setInterval(function() {
ajaxLoop();
}, 2000);
You may use
clearInterval(timerupdateorders);
to end the timer
The error in the title of the post came from jQuery version 1.10.2, line 637
I've got a modal that pops up on a button click with some textboxes and when a button inside the modal is clicked, the information that's in the text boxes is added to a database via AJAX. In order to make the page a little more user-friendly I added a setTimeout function to pause the hiding of the modal so the user can see a verification message that the data was added to the database. Block 1 of my code adds the record to the database, but the setTimeout call doesn't work right:
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
//something about the setTimeout function
//that gives the error in the title
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
//*******this function doesn't run
window.setTimeout(function () {
$('#contact').modal('hide');
$('.modal-body input').each(function () {
$(this).val('');
}, 1000);
});
}
});
}
I fixed it using the code:
(the success function is what we need to pay attention to here)
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body input').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
}
});
}
I see that I in the first block I didn't close the each function, and I fixed that in the second block and that's why it works, but for future reference, what does this error really MEAN in this context?
It means that you left off the second argument to setTimeout and instead passed it as the second argument to .each().
edit — it looks like jQuery is picking up the argument (that 1000) and trying to pass it through to its internal each implementation. The .apply() function expects it to be an array.
I'm making a conversation system where 2 people can chat with each other. I've made an AJAX function which updates the DIV box containing the messages every 2 seconds.
This is working as intended, after a user have written a message. Why isn't the AJAX call being run right away?
// SET AUTORUN updateMessages() EVERY 2 SECONDS
$(document).ready(function() {
var interval
window.onload = function(){
interval = setInterval('updateMessages()', 2000);
};
});
// UPDATE #mail_container_conversation
function updateMessages() {
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/ajaxupdate/<?php echo $user; ?>",
data: dataString,
success: function(data){
$("#mail_container_conversation").html(data);
}
});
}
// SEND NEW MESSAGE
$(function(){
$("#mail_send").submit(function(){
dataString = $("#mail_send").serialize();
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/send",
data: dataString,
success: function(data){
updateMessages();
$(".mail_conversation_answer_input").val('');
}
});
return false;
});
});
You should provide functions instead of strings to setTimeout/setInterval functions. And also there's no need for you to set interval on window load event. You can just keep it as part of DOM ready:
$(function() {
updateMessages(); // don't wait 2 seconds for first update
setInterval(updateMessages, 2000); // update every 2 seconds
});
Everything else seems to should work as expected as long as your posback work when no data is being received (ref dataString).
I hope you do realise that you're using implied globals and understand why that may be a big problem (ref dataString again).
How I would rewrite your code
I would rewrite your whole code into the following that removes implied global variable dataString, doesn't pollute global scope with additional functions and uses setTimeout instead of interval which may in some cases be problematic (although in your case since it' only runs every 2 seconds it shouldn't be a problem if there's no additional very complex client-side script execution)
I've kept everything within function closure local scope:
$(function() {
var timeout = null;
var form = $("#mail_send").submit(function(evt){
evt.preventDefault();
$(".mail_conversation_answer_input", form).val("");
updateMessages();
});
var updateMessages = function() {
// we don'w want submit to interfere with auto-updates
clearTimeout(timeout);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/send",
data: form.serialize(),
success: function(data){
$("#mail_container_conversation").html(data);
timeout = setTimeout(updateMessages, 2000);
}
});
};
// start updating
updateMessages();
});
This code requires your server side (processing on /mail/send) to understand that when nothing is being posted (no data) that it doesn't add empty line in the conversation but rather knows that this is just an update call. This functionality now uses only one server-side URL and not two of them. If you'd still require two, then this code should do the trick:
$(function() {
var timeout = null;
var url = {
update: "<?php echo site_url();?>mail/ajaxupdate/<?php echo $user;?>",
submit: "<?php echo site_url();?>mail/send",
use: "update"
};
var form = $("#mail_send").submit(function(evt){
evt.preventDefault();
url.use = "submit";
$(".mail_conversation_answer_input", form).val("");
updateMessages();
});
var updateMessages = function() {
// we don'w want submit to interfere with auto-updates
clearTimeout(timeout);
$.ajax({
type: "POST",
url: url[url.use],
data: form.serialize(),
success: function(data){
$("#mail_container_conversation").html(data);
url.use = "update";
timeout = setTimeout(updateMessages, 2000);
}
});
};
// start updating
updateMessages();
});
If the rest of your code work, the problem probably is withing this code:
$(document).ready(function() {
var interval
window.onload = function(){
interval = setInterval('updateMessages()', 2000);
};
});
There is no need to attach it to window.onload, since you already wrapped it in a DOM-ready callback.
Remove the single-quotes and the parenthesis from within your call to setInterval
The DOM-ready callback can be shorten, by just passing a function to the jQuery-method.
Try this instead:
$(function () {
setInterval(updateMessages, 2000);
});
Further improvements - Avoid intervals with AJAX:
When dealing with AJAX, you should avoid using intervals, as you may end up stacking calls to the server, if the server takes more than two seconds to respond. setInterval will not care if your server had time to respond or not, it will keep calling it every 2 seconds no matter what.
I suggest that you use a timeout instead, and start a new timeout in the complete-callback of the Ajax-call.
In your case, it could look something like this:
$(function () {
// Make the first call immediately when the DOM is ready
updateMessage();
});
function updateMessages() {
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/ajaxupdate/<?php echo $user; ?>",
data: dataString,
success: function(data){
$("#mail_container_conversation").html(data);
// Make a new call, 2 seconds after you've
// received a successful respose
setTimeout(updateMessages, 2000);
}
});
}
The problem is that updateMessages() tries to send datastring to the server, but this doesn't get filled in until the .submit() function runs.
I don't know what you should put in there, since I don't know what the mail/ajaxupdate script expects. If this is called when nothing happens, I suspect no form data is needed at all, so you can give an empty string.
I'll bet if you checked the Javascript console you'd see some error messages about trying to serialize undefined.
give a try with
$(document).ready(function() {
setInterval('updateMessages()', 2000);
});
You don't need the window.onload in your document ready call.
$(document).ready(function() {
setInterval('updateMessages()', 2000);
});
That should be enough to get it started.
As it is now, once the DOM is ready, you're then asking it to wait for the window to load.. but by that point it's already loaded, so nothing happens.