Recursive ajax() requests - javascript

I use jQuery's ajax()to get information. I call the method when the request is successful. Here is the code:
function recursively_ajax(){
console.warn("begin");
$.ajax({
type:"GET",
url: "./JvmInfoClass",
success: function(data){
console.warn("get jvm info success");
recursively_ajax();
}
});
}
recursively_ajax();
I make the thread sleep 3 seconds in the back-end. But the console print the message continuously not after 3 seconds. Why is this?

You can try this with ajax call async:false
var counter=0;
function recursively_ajax()
{
var pass_data=5;
var chartMenu=['VTR','NC','RC','TOCU','TOCO','TR','COA','MP'];
$.ajax({
type:"POST",
async:false, // set async false to wait for previous response
url: "url to server",
dataType:"json",
data:{dataMenu:pass_data},
success: function(data)
{
counter++;
if(counter < chartMenu.length){
recursively_ajax();
}
}
});
}
recursively_ajax();

in that case the bug is in the server side code because the server should sent back the response only after 3 seconds.
But I would recommend to use setTimeout() in the client side to restrict the request frequency
Try
function recursively_ajax(){
console.warn("begin");
$.ajax({
type:"GET",
url: "./JvmInfoClass",
success: function(data){
console.warn("get jvm info success");
setTimeout(recursively_ajax, 3000)
}
});
}
recursively_ajax();

It's browser's cacheing problem,I append the date to the url or set the ajax cache:false,the problem is solved.Thank everyone.

Related

Call python function with ajax and flask continously

I need to call flask function in python with ajax continously. To that I have following script in html file.
<script >
var ajaxFUN = function () {
$.ajax({
url: '/toAjax',
dataType: 'json',
success: function (data) {
console.log('get info');
$('#data').html(data['data']);
}
});
}
setTimeout(ajaxFUN, 1);
</script>
And here is the python code
#app.route('/toAjax')
def ajaxTo():
print("AJAX WAS HERE")
data= reader.getToAjax()
info = {
"data": data
}
return jsonify(info)
I need to call /toAjax header route in the python continously without hitting any button or any kind of method.
But that implementation prints only once AJAX WAS HERE. Where is the missing part ? How can I fix it ?
Here is the similiar questions which I have looked:
setTimeout() and setting parameters
how to make ajax calls continuously for 5 seconds once
setTimeout triggers exactly once (unless cancelled)
you could use setInterval, but that's likely to flood your server at the rate you've used for setTimeout
I would recommend the following
var ajaxFUN = function () {
$.ajax({
url: '/toAjax',
dataType: 'json',
success: function (data) {
console.log('get info');
$('#data').html(data['data']);
ajaxFUN(); // this calls the function again
}
});
}
ajaxFUN();
In case you're worried, there's no "recursion", since ajaxFUN() is being called in an asynchronous callback

Retrieve comments on runtime?

I want to call Ajax which fetches all the comments from database.
Now how to put a check on that Ajax Script to Run, when only someone comments.
Same as the stackoverflow notifications. When we comment on question, The Notification appears without reloading page (i.e On Runtime ).
Right now I am Running the same Ajax Script after each 10 seconds again and again, when I think is a bad way .So Here is my working Ajax Code:
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: "GET",
url: "ajax_files/reload_notifications.php"
}).done(function(result) {
var $notifications = $('#notification_area');
if ($notifications.length > 0) {
$notifications.html(result);
}
});
}, 10000);
});
When a comment is entered, do a similar AJAX request that will save the comment and on it's success callback, call another function which will also hit another AJAX request which fetches the comments. For e.g.
function insertComment() {
$.ajax({
type: "GET",
url: "ajax_files/insert_comment.php"
}).done(function(result) {
fetchComments();
}
});
}
function fetchComments() {
$.ajax({
type: "GET",
url: "ajax_files/reload_notifications.php"
}).done(function(result) {
var $notifications = $('#notification_area');
if ($notifications.length > 0) {
$notifications.html(result);
}
});
}
Hope this helps!

Trigger success handler is finished executing, with nested ajax requests

I have many nested ajax requests like below. I have a lot of things going on in the success function below, I need something like success that will trigger when success is complete. complete(jqXHR, textStatus) just seems to fire with success and I don't think .ajaxComplete() works.
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function (d1) {
//more nested ajax requests
},
});
SOLUTION:
A $.ajax() replacement plugin called $.fajax() (finished + ajax) has been created. Please check it out and let me know what you think. https://github.com/reggi/fajax (It's pretty well documented).
You could create a wrapper function for jQuery.ajax to make this a little cleaner:
var started = 0, done = 0;
var globalHandler = function(){
//do stuff when all success handlers are done
}
function handleAjax(args){
var _success = args.success || function(){};
args.success = function(jqXHR, textStatus){
_success(jqXHR, textStatus);
done++;
if(done >= started)
globalHandler();
}
var ajax = $.ajax(args);
started++;
return ajax;
}
usage
handleAjax({
url: 'api/periods.json',
dataType: 'json',
success: function (d1) {
//more nested ajax requests like this:
handleAjax({...});
}
});
This creates a closure so don't do any crazy memory-intensive stuff in there and you should be fine.
I'm not quite totally sure of what you're asking, so forgive me if I'm off-kilter, but I think you might want something like:
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
//more nested ajax requests
},
}).done(function(msg){
alert("Every Ajax Call is Complete!");
});
You may want .queue() or .Defered
$("#el").queue("queue_name",function(){
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
//more nested ajax requests
$("#el").dequeue("queue_name"); // tell queue success is complete
},
});
}).queue("queue_name",function(){
//do something you want when success is complete
})
$("#el").dequeue("queue_name"); // start to execute
or $.Deferred()
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
var start = function(){
var dtd = $.Deferred();
//more nested ajax requests---------------
$.post("xxx",function(){
dtd.resolve(); // when success is complete
});
//----------------------------------------
return dtd.promise();
}
start.apply(this).pipe(function(){
//do something you want when success is complete
});
},
});

How do you repeatedly make an ajax request with jquery?

I have the following ajax request that runs when the page is loaded
var city_id = $(".feed-selected-city").attr('id');
$("#cityfeed").html("<div class='feed-loading'>The feed is loading ...</div>");
var ajaxOpts = {
type: "get",
url: "ajax_getcityfeed.php",
dataType: 'json',
data: "&city=" + city_id,
success: function(data) {
$('#cityfeed').html(data.data);
}
};
$.ajax(ajaxOpts);
How can I run this piece of code every 10 seconds after that?
Wrap it in a function, and use setTimeout to continuously call the function.
function tick() {
var city_id = $(".feed-selected-city").attr('id');
$("#cityfeed").html("<div class='feed-loading'>The feed is loading ...</div>");
var ajaxOpts = {
type: "get",
url: "ajax_getcityfeed.php",
dataType: 'json',
data: "&city=" + city_id,
success: function(data) {
$('#cityfeed').html(data.data);
}
};
$.ajax(ajaxOpts);
setTimeout('tick()',10000);
}
$(document).ready(function() {
tick();
}
#Yegor
Wrap the above function using a name. Then use setTimeout(function(){//call the function here},10000); -
I would suggest you not to make this kind of implementation. Make some alternative.
Use a infinite loop with setTimeout. And put that inside.
Though I don't recommend this to achieve what you're trying todo. I think what you require is some kind of polling; this will probably kill your server if there's a high amount of simultaneous users; since each visitor will send a http request every 10 seconds.
function timedCount()
{
console.log('Hello');
setTimeout("timedCount()",10000);
}
timedCount();

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf

Categories

Resources