Call python function with ajax and flask continously - javascript

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

Related

If statement in jQuery and HTML?

I m running the following script with success : it updates the text every 3s
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
window.setInterval(function() {
loadNewText()
}, 3000)
function loadNewText() {
$.ajax({
url: "/update_report",
type: "POST",
dataType: "json",
success: function(data) {
$(report).replaceWith(data)
}
});
}
});
</script>
I want to change the function in HTML to run 'loadNewText()' only if there's changes in certain variable in Python code !
I've put the variables in python route :
#app.route('/console-output')
def console_output():
fileHandle = open("console_output.txt", "r")
lineList = fileHandle.readlines()
fileHandle.close()
last= lineList[len(lineList)-1]
with open('console_output.txt', 'r') as r:
co =r.read()
return render_template("console-output.html",console_output_msg=console_output_msg, last=last, co=co)
and write the following code in HTML :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
if (last != console_output_msg) {
loadNewText();
}
function loadNewText() {
$.ajax({
url: "/update_text",
type: "POST",
dataType: "json",
success: function(data) {
$(new_text).replaceWith(data)
}
});
}
});
</script>
This method is not working ! I don't have a big experience with Javascript! I don't know if I m not calling the variables (last, console_output_msg) the right way or my function is not valide !
If there's any way to correct it or any other suggestion to call 'loadNewText()' when changes happens in python code !
Thanks!
There are 2 popular ways to update the text when there is a change in Python:
Long polling
Using setInterval() function to trigger an ajax call to the server to check if there are any changes.
WebSocket
Implement a WebSocket connection between the server and browser. Receive the message sent from the server.
Link for implement WebSocket in Python.
https://websockets.readthedocs.io/en/8.1/intro.html
You can't access server variables on the client.
You could save the previous output in a JavaScript variable, and only update the DOM if it has changed. You need to put the if statement inside the loadNewText() function, after it has received the response, so it can compare it.
This won't skip the AJAX call, but it will avoid refreshing the page when nothing has changed.
$(function() {
let last_output;
window.setInterval(loadNewText, 3000)
function loadNewText() {
$.ajax({
url: "/update_report",
type: "POST",
dataType: "json",
success: function(data) {
if (data != last_output) {
$(report).replaceWith(data);
last_output = data;
}
}
});
}
});

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

Recursive ajax() requests

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.

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