0

In index.html, I'm getting a value stored in localStorage:

    <script>
        function checkChannel() {
                        if (localStorage.getItem('channel')) {
                            const channel = localStorage.getItem('channel');
                            const request = new XMLHttpRequest();
                            request.open('POST', '/convert');
                            // Add data to send with request
                            const data = new FormData();
                            data.append('channel', channel);

                            // Send request
                            request.send(data);
                         }
        }
    </script>
</head>

<body onload="checkChannel()">
    .
    .
    .

This works fine. It is routed to the code below in application.py. The debugger hits the first line in convert() below, so I know it's getting there.

@app.route("/convert", methods=["POST"])
def convert():
    channel = request.form.get("channel")
    channel_messages = channels_dict[channel]
    return render_template("channel.html", channel=channel, channel_messages=channel_messages)

However, channel.html is not being rendered. Instead, it stays on the same page. What am I doing wrong here? I can give more details if needed.

Paul Reiners
  • 8,576
  • 33
  • 117
  • 202

1 Answers1

1

You need to define a request.onload() function. This function will be called after the response is received. so your JS code will be similar to this:

function checkChannel() {
  if (localStorage.getItem('channel')) {
      const channel = localStorage.getItem('channel');
      const request = new XMLHttpRequest();
      request.open('POST', '/convert');
      // Add data to send with request
      const data = new FormData();
      data.append('channel', channel);

     // Send request
     request.send(data);

     // 4. This will be called after the response is received
     request.onload = function() {
       if (request.status != 200) {
          // analyze HTTP status of the response
          alert(`Error ${request.status}: ${request.statusText}`);
          // e.g. 404: Not Found
       } else { // show the result
          $('body').html(request.response)
       }
     };
  }
}

Please note that you can replace $('body').html('some content') by $('div').html('some content') or $('#some-id').html('some content') based on channel.html file content.

Please find this example.

ASSILI Taher
  • 1,210
  • 2
  • 9
  • 11