If statement in jQuery and HTML?

Viewed 111

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!

2 Answers

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

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

Related