How can I run the function after the effect is done like delaying running the specified function after a certain time? I tried set timeout and it didn't work for me.
Here my Code
<script>
$("#findtext").keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13)
{
explodeEffect();
}
$.ajax({
url: 'resultFindFriend.php',
type: 'post',
async: false,
data: { dataFriend: $(this).val() },
success: function (data) {
$('.outputfindfriend').html(data);
}
},setTimeout(150));
});
function explodeEffect() {
$("#explodesearchresult").toggle("explode");
setTimeout(1000);
window.location("http://localhost/index.html");
};
$("#buttonfriend").click(function () {
explodeEffect();
return false;
});
</script>
This is doable with jQuery's .toggle(), just add a function as the second argument.
Try this:
function explodeEffect() {
$("#explodesearchresult").toggle(400, function() {
setTimeout(function() {
window.location.href = "http://localhost/index.html";
}, 1000);
});
}
This will redirect the page 1 second after the explode effect has finished.
Related
I want to call ajax function at specified intervals after enterkey being pressed.
However, the code doesn't work.
I want to get some advice.
Thank you!
function regist(){
$.ajax({
url: '/getlabel',
method: 'GET'
}).done(function(r){
// console.log(r);
$('#label').text(r)
console.log("ajax-success")
}).fail(function(){
console.log("ajax fail")
});
}
function keyPress(e) {
if (e.keyCode == 13) {
setInterval( regist() , 3000);
return false;
}
}
I have a code that determines if current browser window or tab is active. If it's active, the title of the tab says "active" and if not it says "blurred"
It is working fine. Here's the code:
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
document.title = 'focus';
}
}
$(this).data("prevType", e.type);
})
The code above is working fine.
Now if I add AJAX to it, it doesn't work.
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
var interval = function () {
$.ajax({
url: "<?php echo base_url('home/get') ?>",
cache: false,
success: function (html) {
$("#text").val(html);
document.title ='focus';
},
});
};
setInterval(interval, <?php echo $int ?>);
}
}
$(this).data("prevType", e.type);
})
It says focused if it's in focus. If I go out of focus, it says "blurred" for less than a second, then says focus again. I don't know why. I want it to say blurred if it's not in focus. Adding the AJAX code doesn't make it work.
Please help. Thanks.
You need to use clearTimeout() in your blur event. My code continuously polls my server for data, but when I go out of the page, it stops polling. Please look at the implementation below. I have done the similar one in my application here:
$(window).blur(function() {
clearTimeout(getJsonTmr);
clearTimeout(updatePreviewTmr);
}).focus(StartTimers);
function StartTimers () {
// Every half a second,
getJsonTmr = setInterval(function () {
$.get("/doodles/update?getJson&DoodleID=" + DoodleOptions.DoodleID, function (data) {
data = JSON.parse(data);
if (!DoodleOptions.isActive)
clearDoodleCanvas();
$.each(data, function (index) {
drawFromStream(data[index]);
});
});
}, 500);
updatePreviewTmr = setInterval(function () {
$.post("/doodles/update?updatePreview", {
"DoodleID": DoodleOptions.DoodleID,
"DoodlePreview": canvas.toDataURL()
});
}, 5000);
}
StartTimers();
You can use the above code as reference and change yours.
A simple reference implementation for you...
function timers() {
tmrAjax = setInterval(function () {
$.get(/* ... */);
}, 1000);
}
timers();
$(window).blur(function () {
clearInterval(tmrAjax);
}).focus(timers);
I've following two functions in jQuery:
$(document).on('change','.states',function(){
//on change of select
});
$(document).on('click','.date_control',function(){
//on click of input .date_control
});
How to combine the above two functions into one function so that I can use it with my AJAX function which is as below:
$(function() {
$(".add_new_rebate").on("click", function(event) {
event.preventDefault();
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
});
});
If you have any other way than combining the above two function into one then also it will be fine. My requirement is to incorporate the code of these two functions into the above AJAX function as I'm generating the two HTML controls dynamically and I want to apply the jQuery classes to them. Thanks in advance.
JS:
function do_action(){
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
}
$(document).on('change','.states',function(){
//on change of select
do_action();
return false;
});
$(document).on('click','.date_control',function(){
//on click of input .date_control
do_action();
return false;
});
I'm assuming the reason why you asked the question is to avoid using the same code inside both events, this way, it's much cleaner. No repeating.
I am not that sure if I understood the point correctly, but I you can define a function withName () {}, so you can reference that function from withing the event handlers.
Here doStuff is called either on »change« or on »click«
function doStuff (e) {
//the stuff to do
}
$(document).on('change','.states', doStuff);
$(document).on('click','.date_control',doStuff);
I hope that is what you are asking for…
Please see this link:
How to combine two jQuery functions?
And the answer can answer your question:
you simply use the same selector for both your action and your confirm
function handler(event) {
event.preventDefault();
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
}
$(document).on('change','.states', handler);
$(document).on('click','.date_control', handler);
If I understood your requirement correctly, then the following should work:
$( '.states, .date_control' ).on( 'click change', function ( event ) {
if( ( event.type == 'change' && event.target.className == 'states' )
|| ( event.type == 'click' && event.target.className == 'date_control' ) ) {
//process event here
};
} );
<script type="text/javascript">
var timeOutID = 0;
var checkScores = function() {
$.ajax({
url: "<?php echo 'http://127.0.0.1/ProgVsProg/main/countScoreCh'?>",
success:function(response){
if (response !=' ') {
$('#scoreCh').html(response);
clearTimeout(timeOutID);
} else{
timeOutID = setTimeout(checkScores, 3000);
}
});
}
timeOutID = setTimeout(checkScores,1000);
</script>
I am using setTimeout if there is a change in the database. If there is a change..it will output the change.
My problem is setTimeout will only display the first call.and never checks again if there is another change in the database.
I don't know if setTimeout is the correct way of doing it.
Yeah, setTimeout only runs once though. You're looking for setInterval.
<script type="text/javascript">
var timeOutID = 0;
var checkScores = function() {
$.ajax({
url: "<?php echo 'http://127.0.0.1/ProgVsProg/main/countScoreCh'?>",
success: function(response) {
if(response !== '') {
$('#scoreCh').html(response);
}
}
});
};
timeOutID = setInterval(checkScores, 1000);
</script>
You could also get it working by just getting rid of that else in your success function:
success: function(response) {
if(response !== '') {
$('#scoreCh').html(response);
}
timeOutID = setTimeout(checkScores, 3000);
},
error: function() {
timeOutID = setTimeout(checkScores, 3000);
}
You are making these mistakes
If you want to poll for database changes, don't use setTimeout. Instead use setInterval and clear this interval depending upon your logic like after 50times or something else.
Use a busyFlag because you are making an asynchronous call. (As suggested by #mike)
Try this
var intervalId = null;
var IS_BUSY_FETCHING_UPDATES = false;
var checkScores = function() {
if (!IS_BUSY_FETCHING_UPDTAES) {
IS_BUSY_FETCHING_UPDTAES = true;
$.ajax({
url: "http://127.0.0.1/ProgVsProg/main/countScoreCh"
}).done(function(response){
if (response) {
$('#scoreCh').html(response);
}
}).fail(function(e) {
console.error(e);
}).always(function() {
IS_BUSY_FETCHING_UPDATES = false; // This will be executed when AJAX gets complete
});
}
intervalID = setInterval(checkScores,1000);
I use the function below to check on the status of a JSON file. It runs every 8 seconds (using setTimeout) to check if the file has changed. Once the JSON's status becomes 'success' I no longer want to keep calling the function. Can someone please show me how to do this? I suspect it involves the use of clearTimeout, but I'm unsure how to implement this.
Cheers!
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
}
},
}).always(function () {
setTimeout(checkBookStatus, 8000);
});
};
checkBookStatus();
});
t = setTimeout(checkBookStatus, 8000); when you decide to stop the timeout use this clearTimeout(t);.
use clearTimeout
e.g. you defined :
id = setTimeout(checkBookStatus, 8000);
then you can remove this function by :
clearTimeout(id)
Before your call of checkBookStatus() at the end, put another call: var interval = setInterval(checkBookStatus, 8000);. Then on success you can clearInterval(interval).
Do not use setTimeout for iteration.
A lot of answers are suggesting just to use clearTimeout() however, you are checking the status after the timeout has expired, there is no timeout to clear. You need to not call setTimeout() in your always() function rather than to clear anything. So you could re-inspect the status inside your always() function I suppose, but your data object isn't in scope there. It would be preferable to just use setInterval() outside of your checkBookStatus() function.
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
clearInterval(interval);
}
}
});
};
var interval = setInterval(checkBookStatus, 8000);
checkBookStatus();
});
Call clearTimeout with the value previously returned by setTimeout. This would give you something like:
$(function() {
var timeoutID;
var checkBookStatus = function () {
[…]
else if (data.status == "#{Job.success}") {
clearTimeout(timeoutID);
[…]
}).always(function () {
timeoutID = setTimeout(checkBookStatus, 8000);
[…]
When you use setTimeout, use like this:
var myTime = setTimeout(checkBookStatus, 8000);
to clear it just:
clearTimeout(myTime);
the following should work...
the setTimeout function return an instance of the setTimeout function. Keep this value in a variable and pass it to the function clearTimeout when you want to prevent the event from firing again.
i.e.
var t = setTimeout(1000, someFunction);
...
//after you no longer need the timeout to fire, call
clearTimeout(t);