skip to Main Content

I am a starting with flask/html/javascript and I have this issue:

I render a template from python:

return render_template("loading.html", process='abc')

This es the content of loading.html file

<body>
<div class="titulo">
    <p>here I see the value of parameter sent {{process}}</p>
</div>
    <div class="loader">
</div>

<script>
function navigate() {
    window.location.href = 'process_b';
}
fetch('process_a').then(navigate);
</script>
</body>

This small code works fine it executes process_a then process_b but the question is: How can I use the parameter "process" inside the javascript?
I have tried using:

document.getElementById("process").value

but it does not work

Can someone please help me?

Best regards

document.getElementById("process").value

3

Answers


  1. You need to parse the HTML that’s returned from the API.

    function navigate(html) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      let process = doc.querySelector(".titulo p").innerText;
      console.log(process);
    }
    
    fetch('process_a')
      .then(res => res.text())
      .then(navigate);

    The value is in the text of a <p> tag, not the value of an input.

    Login or Signup to reply.
  2. You can inject values for JavaScript like this:

    <script>
      let process = "{{ process }}";
    </script>
    

    That is for a string. If it is a number, you don’t need the quotes.

    Login or Signup to reply.
  3. It can be achieved by making a small change in the template code as below

    <div class="titulo">
        <p>here I see the value of parameter sent <span id="process">{{process}}</span></p>
    </div>
    

    I have added span tag with id attribute with value = process which can be now accessed in javascript by using the below code.

    document.getElementById("process").value
    

    Hope it solves your issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search