jquery setinterval time with ajax - php

I want to auto refresh "result" div with ajax & setInterval function.
But there is a one problem. I want auto-refresh in 500ms but sometimes ajax loading more than 500ms. In this cases consists problem. I want to if ajax loading time 750ms then interval time 750 (or any time longer 500ms) else 500. How can I do this ?
var refreshId = setInterval(function()
{
var number=$("#number").html();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: 'num='+number,
success: function(ajaxResult) {
$('#result').html(ajaxResult);
}
});
if(number<100){
number++;
$("#number").html(number);
}
}, 500);

Use setTimeout instead of setInterval. Set timeout function inside ajax response function, and you won't have problems with syncronizing server calls.
(function pollStep(){
var number=$("#number").html();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: 'num='+number,
success: function(ajaxResult) {
$('#result').html(ajaxResult);
setTimeout(pollStep, 500);
}
});
if(number<100){
number++;
$("#number").html(number);
}
})();

Try the condition within success function.
success: function(ajaxResult) {
$('#result').html(ajaxResult);
if(number<100){
number++;
$("#number").html(number);
}
}

Related

How delay ajax call by few seconds

I'm not sure this is the best way to send 2 ajax togheter for facebook api.
But it works, the problem is that sometimes i get the second ajax (result_flow.php) before the first (result.php)
Will be helpful delay second ajax (url:result_flow.php) for 3 seconds or change this code in someway to give a order.
I tried setTimeout but didn't work.
$('#sub').click(function () {
var data = $("input#dataInput").val();
console.log(data);
var total = $("input#totalInput").val();
var subscriber_id = $("input#subscriber_id").val();
var res_name = $("input#res_name").val();
var dataString = 'data='+ data + '&total=' + total + '&subscriber_id=' + subscriber_id+ '&res_name=' + res_name;
console.log(dataString);
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
success: function(data) {
console.log(data);
if(data==='success'){
//localStorage.clear();
MessengerExtensions.requestCloseBrowser(function success() {
console.log("Webview closing");
}, function error(err) {
console.log(err);
});
}
}
});
$.ajax({
type: "POST",
url: "result_flow.php",
data: dataString,
success: function(data) {
setTimeout(function(){
console.log(data);
if(data==='success'){
}
},3000);
}
});
}
I would suggest to use async/await nowadays, it is quite easy to use AJAX calls sequencially:
$('#sub').click(async () => {
...
try {
let data = await $.post({
url: "result.php",
data: dataString
});
if (data === 'success') {
...
}
data = await $.post({
url: "result_flow.php",
data: dataString
});
if (data === 'success') {
...
}
} catch (err) {
console.log(err);
}
});
Not tested, as i donĀ“t work with jQuery - but it should give you the idea. Since $.ajax/$.post supports Promises, it should work with async/await. Be aware that you may need to transpile your code with Babel for older browsers, but i suggest using Babel anyway.
If you want to use both AJAX calls in parallel, use Promise.all (because they do not depend on each other) - the results will be in order, so you can make sure the callback code is called in order.
First, setTimeout() is not working because you put it inside the callback, which means it will be executed when the request is already done. Anyway that's not a proper way to handle such a task, you should put the second request inside the first's callback, so that it will be executed as the first one finishes.
The code looks like this:
$('#sub').click(function() {
var data = $("input#dataInput").val();
console.log(data);
var total = $("input#totalInput").val();
var subscriber_id = $("input#subscriber_id").val();
var res_name = $("input#res_name").val();
var dataString = 'data=' + data + '&total=' + total + '&subscriber_id=' + subscriber_id + '&res_name=' + res_name;
console.log(dataString);
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
success: function(data) {
console.log(data);
if (data === 'success') {
//localStorage.clear();
MessengerExtensions.requestCloseBrowser(function success() {
console.log("Webview closing");
}, function error(err) {
console.log(err);
});
$.ajax({
type: "POST",
url: "result_flow.php",
data: dataString,
success: function(data) {
console.log(data);
}
});
}
}
});
}
Note that in my code the second request is sent just if the first one is successful because it's placed within the if (data === 'success') {...} statement.
You should call them in chain. Success... then... using promise is the best way.
Never trust the order you receive if is not explicitly written by you.
JQuery Ajax
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
You can do something like this:
// First Ajax call
$.ajax({
// Do the request
// Remove success to use new promise
})
.done(function( data ) {
// Add the success here
// Add the Second Ajax call here or create a function to call it, whatever you want
});

Jquery Stop Load and Clear Interval

I'm using jquery to load an external page and display it in a DIV called View.
I have 2 buttons Go & Stop.
This is working, but when I click stop it can take a few seconds.
Any way to make it stop straight away ?
$("#Go").click(function () {
$("#view").load("test.php");
refreshId = setInterval(function() {
$("#view").load("test.php"); }, 1000);
});
$("#Stop").click(function () {
clearInterval(refreshId); $("#view").stop();
$.ajax({ url : 'new.php' });
} });
Thanks :)
you can try:
var xhr = $.ajax({
type: "POST",
url: "test.php",
data: "name=John&location=Boston",
success: function(msg){
$("#view").html(msg);
}
});
and stop call:
//kill the request
xhr.abort()

Adding Setinterval and clear interval to my query

I have a counter where in member can add or remove his number which gets saved in mysql.
i am using the following jquery/ajax to call the function when member clicks on adding or removing. But sometimes removing does not give the exact count, am planning to use setinterval and clearinterval. And also I need to use set interval once, for example, it should query the file only once with in 5 seconds or exact 5 seconds. but below setinterval and clearinterval does not seem to work,
$(function () {
var checkit = function () {
$(".addid").click(function () {
var add_id = $(this).attr("id");
var dataString = 'add_id=' + add_id;
$(".add_show" + add_id).fadeIn(400).html('Updating...');
$.ajax({
type: "POST",
url: "num_check.php",
data: dataString,
cache: false,
success: function (html) {
$(".add_show" + add_id).html(html);
window.clearInterval(nre);
}
});
return false;
});
}
var nre = setInterval(checkit, 5000);
});
Advise and help will be much appreciated
You can modify the Ajax call as -
$.ajax({
type: "POST",
url: "num_check.php",
data: dataString,
cache: false,
async : false,
success: function (html) {
$(".add_show" + add_id).html(html);
window.clearInterval(nre);
}
});
With this, the next Ajax call will not start until the current one has been completed. It should do the trick.

Ajax program is not running as I expect

Ajax program is not running as I expect. See the code
$(document).ready(function(){
$("input").keyup(function() {
for(var i=400;i<421;i++){
(function(counter){
counter=String(counter);
$.ajax({
type: "GET",
url: "results/result_html.php?usn="+txt+counter+"&resultType="+resultType,
dataType:"JSON",
success:function(result){
$("#info").hide();
$("#result").html(result);
$("#usn").attr("placeholder", "Class USN");
}
});
})(i);
}
alert("hai");
});});
In this code I want to show the alert after completing all Ajax request which is in that for loop. But when I run this code alert is showing first. I'm new to Ajax please can anyone help me to run as I expected.
Ajax is Asynchronous which means, it will continue running the code in parallel. The success function is called after the Ajax request is complete. What you can do is this:
$(document).ready(function(){
$("input").keyup(function() {
var loopsToDo = 20, done=0;
for(var i=400;i<421;i++){
var counter=String(i);
$.ajax({
type: "GET",
url: "results/result_html.php?usn="+txt+counter+"&resultType="+resultType,
dataType:"JSON",
success:function(result){
$("#info").hide();
$("#result").html(result);
$("#usn").attr("placeholder", "Class USN");
},
complete : function(){
done++;
if( done == loopsToDo)
{
alert("DONE")
}
}
});
}
});});
Your code is weird. Why does it go
for(var i=400;i<421;i++)
Also, the alert will display first before any of the Ajax calls, because ajax is Asynchronous, meaning it runs seperately to the rest of the code. Since you are running 20 Ajax requests, the alert does not wait for all 20 to complete. What you need to do is keep a count of the Ajax calls in your success part and when that equals 20 then display an alert.
Because AJAX calls are asynchronous, it will set up the AJAX call, then continue to execute the script. The 'success' parameter specifies the callback to use once a response is received - which could happen at any time (hence, asynchronous).
$(document).ready(function(){
$("input").keyup(function() {
for(var i=400;i<421;i++){
(function(counter){
counter=String(counter);
$.ajax({
type: "GET",
url: "results/result_html.php?usn="+txt+counter+"&resultType="+resultType,
dataType:"JSON",
success:function(result){
$("#info").hide();
$("#result").html(result);
$("#usn").attr("placeholder", "Class USN");
alert("hai");
}
});
})(i);
}
});
});
That should solve your problems.

Calling AJAX from jQuery and displaying a waiting message

I'm very new at AJAX calls from jQuery and I'm a bit stuck trying do to this; I have an AJAX call from jQuery like this:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {//the_output_here}});
});
});
This script is inside a web page triggered when the user hits a particular row (<tr></tr>) from a table. stats-render.php outputs HTML text with some info and graphics. This answer some times takes a while (15 seconds), so I would like to show the user a waiting message when he/she triggers the script and when the call returns an answer show the output text in a div (lets call it <div id="render-div">).
So the questions are, how can I show a waiting message? If you know a good script for showing this in a modal, I would appreciate it.
How can I output the result from stats-render.php into a div?. Thank you so munch for any help!
Just display a loading message in the div where the results go in the interim.
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) { $('div.for-results').html( /* d... */ ); });
$('div.for-results').html('loading...');
});
});
Or for even more fun:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
clearInterval(loading);
$('div.for-results').html( /* d... */ );
});
$('div.for-results').html('loading');
var loading = setInterval(function() { $('div.for-results')[0].innerHTML += '.' }, 1000);
});
});
The easiest option is probably to check out the jquery-loading plugin.
I just do a simple show the message before the call, and hide it on the success callback like this:
However I think jquery might have a callback option when the ajax call starts, and when it stops.
$(document).ready(function() {
$('tr.table-row').click(function(){
//Show the loading message, or chage a css class, or what have you.
$('#loadingmessagetext').show();
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
//Hide the loading message
$('#loadingmessagetext').hide();
//the_output_here
}
});
});
});

Categories