1

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

1
  • 1
    setTimeout(ajaxFUN, 1); calls it once - and I wouldn't use setInterval with an interval of 1, that would be ridiculous - hint: add ajaxFUN() after the line $('#data').html(data['data']); to call the function again once the previous request is done Commented Sep 19, 2019 at 8:03

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much it worked. But I have question, using this kind of code is it appropriate for application ?
depends on what you mean by "this kind of code" - do you mean "code that does what you want"?
Yes exactly code that does what I want, because I am new in this area, and stackoverflow is only my guidleline. Thanks for your contribution. Therefore I am not sure whether it is ok or not
@GhostDede - well, the only reason this may not be "appropriate" is if the server can't handle the constant requests

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.