auto load in ajax jquery on every one minute - javascript

$('.msg_block').on('click', 'section.msgholder', function(event) {
var clickedItem = $(this).attr('id');
var id = jQuery(this).data('value');
var date = jQuery(this).data('date');
$.ajax({
type:"POST",
url:"/Messages/messageDetails",
data: {id: id, ddate: date},
beforeSend: function()
{
},
success : function(response) {
// Do all my stuff here
},
error : function() {
alert('error');
}
});
});
This is my simple jquery ajax call to the server. Now i want to fire this ajax request every second. Could anyone please help me in this.
Any help would be appreciable.

Try this to call your AJAX function after every one minute
$(document).ready(function () {
setInterval(function () {
SomeFunction();
}, 60000); // 1000 ==> 1 second
});
function SomeFunction() {
$(".msg_block").click();
}

You can use setInterval. Look:
window.setInterval(event, 60000); // It will call the function every 1 min
And function event would be
function event() {
$(".msg_block").click(); // it will click that class so ajax function called
}

Related

Prevent ajax returning fail, for frequently request?

I'm working with ajax to get some data. The problem is ajax request was coming from hovering a button so that can be very easily to spam the request that may lead to fail error 404 or error 500. This is my ajax code :
$.ajax({
url: location.origin+'/getcat',
data : {
't': id
},
success: function(){ alert("I'm handsome"); }
});
The question is how to prevent this spam request?
You could make it with setTimeout():
$(document).ready(function(){
var timer;
var delay = 1000;
$("p").hover(function(){
timer = setTimeout(function() {
console.log("Requesting")
$.ajax({
url: location.origin+'/getcat',
data : {
't': id
},
success: function(data){
alert('Im handsome');
}
});
}, delay);
}, function(){
clearTimeout(timer);
console.log("Canceled request")
});
});
You could use .one() which will only use the event handler once. Then you can execute that .one() again, when a cool-down period has expired.
(function enableRequests() {
console.log("listening for next mouse move");
$('#spn').one("mousemove", function() {
console.log("launching request, and cooling down for 5 seconds");
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
success: function () { console.log('response from server') }
});
setTimeout(enableRequests, 5000); // 5 second cooldown period
});
})(); // execute immediately
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="spn">Hover here</span>

Is possible in on click function in jQuery wait for ajax complete and then do some code?

I want show modal after ajax is complete, here is my code:
$('.mymodalbtn').on('click', function (e) {
modalWindow = $(this).attr('data-target');
// alert(modalWindow);
$(document).ajaxStop(function () {
//0 === $.active
$(modalWindow).modal('show');
});
});
It is possible to do that? Now modal show after every ajax complete.
Thank you.
You can use .ajaxComplete() method of ajax request,which registers a handler to be called when Ajax request is completed.
Read more here.
Use complete event when your ajax call completed.
$('.mymodalbtn').on('click', function (e) {
modalWindow = $(this).attr('data-target');
$.ajax({
type: 'GET',
url: 'your_url',
success: function (responseData, textStatus) {
},
complete: function (textStatus) {
$(modalWindow).modal('show');
},
error: function (responseData)
{
}
});
});
I'm not sure about the way you're doing an ajax call, but I've been able to do it with the post super global
$_post(phpfile.php, $_post(phpfile.php, {variables to send}, function) you can use data as a parameter for the function and it will be anything that PHP echoes including error messages
Thank you for inspiration finally I do it this way.
global variable:
window.modal = "";
on click function:
$('.mymodalbtn').on('click', function (e) {
modalWindow = $(this).attr('data-target');
window.modal = modalWindow;
});
and ajax complete:
$(document).ajaxComplete(function (event, request, settings) {
if(window.modal != ""){
$(window.modal).modal('show');
window.modal = "";
}
});
Hope it is allright :-)
try to use setTimeout.
setTimeout(function(){
$('#mymodal').modal('show');
},4000);
Yes it is possible. You can use .ajaxStop() or .ajaxComplete() or in .ajaxSuccess()

How to make setInterval run when browser tab is on focus?

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);
});
});

auto refresh div every x seconds and stop to successsful load

I need to create a div that will auto refresh every 10 seconds, and stop when it successfully loads. I created this jQuery script:
<script type="text/javascript">
$(document).ready(function(){
var j = jQuery.noConflict();
j(document).ready(function()
{
j(".refresh").everyTime(1000,function(i){
j.ajax({
url: "pin.php",
cache: false,
success: function(html){
j(".refresh").html(html);
}
})
})
});
j('.refresh');
});
</script>
It works but the refresh continues every 10 seconds. I need it to stop if pin.php returns a numeric output.
How can I edit it to stop refresh if pin.php returns a numeric output?
From the documentation over at http://www.jquery-plugins.info/jquery-timers-00013992.htm, the function you need is probably stopTime. Although I haven't tested it, the following in your success should work:
success: function(html) {
if (j.isNumeric(html)) {
j(".refresh").stopTime();
} else {
j(".refresh").html(html);
}
}
Try it with an interval like this, it fires till the loaded call is done then it stops the interval and ajaxcal
$(document).ready(function(){
var j = jQuery.noConflict();
jRefresh();
var jRefresh = setInterval(function(){
ajaxCall()
}, 1000);
function ajaxCall() {
j.ajax({
url: "pin.php",
cache: false,
success: function(html){
if (j.isNumeric(html)) {
myStopFunction();
}
}
})
}
function myStopFunction() {
clearInterval(jRefresh);
}
});
first of all you do not need to call $(document).ready() twice. To aviod conflicts you can write code like this :
jQuery(document).ready(function($){
// Your code here
});
Note the $ parameter
Second, I guess it is unuseful to use everytime ( looks like is a plugin and is not a good idea to load a lot of code since you have good alternatives for your needs ) when you can simply call setInterval;
According to your needs and following what i said above, the code should looks like :
jQuery(document).ready(function($){
var interval_time = 10000;
var interval = null;
var $wrapper = $('.refresh');
interval = setInterval(function(){
$.ajax({
url : 'pin.php',
cache : false,
success : function( html ){
if( $.isNumeric( html ) ){
clearInterval( interval );
}
$wrapper.html( html );
}
})
}, interval_time);
});
You can modify your code something like this:
var temp = setInterval(1000,function(i){
j.ajax({
url: "pin.php",
cache: false,
success: function(html){
if(isNaN(html))
j(".refresh").html(html);
}else{temp.clearInterval();}
})
})
You said, "I need it to stop if pin.php returns a numeric output".
if .refresh html contain number than it stop to call ajax call otherwise it make call.
if(isNaN(j(".refresh").html()){
//put your ajax call in this block
}

ajax jquery update page without refreshing

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

Categories

Resources