Home > Software design >  How to send values from LocalStorage to Flask @app.route()?
How to send values from LocalStorage to Flask @app.route()?

Time:06-10

Recently, i've been using Flask, but i just wanna ask how to POST data from LocalStorage of the web browser to @app.route

part of main.py

@app.route("/authenticate/post", methods=['GET', 'POST'])
def posting():
  posts = request.form['post']
  return render_template("testing.html", post=posts)

Here i'm making a small web-based "posting and sharing app" just like Instagram, the var posts is the Post Content submitted via textarea of html, and is working perfectly fine. All i need now is how to get the data stored on LocalStorage of a user's browser. Which is the Username of the user. How can i retrieve the Username of the user that is stored on the LocalStorage and do POST request to my @app.route()

Index.html

  <div >
  <h5>Write Something &amp; Post!</h5>
    <form method="POST" action = "/authenticate/post" autocomplete="off">

<textarea  placeholder="Say something!" id="post" name="post" rows="4" cols="50" maxlength="200"></textarea>
      <br><br>
<input id="enter" type="submit"  value="Post!" onclick="getname()">
    </form>
</div>

The getname() function of my main.js

function getname() {
    let name = localStorage.getItem('username');
}

CodePudding user response:

I'd change the submit input to a simple button:

<div >
  <h5>Write Something &amp; Post!</h5>
    <form id="post-form" method="POST" action = "/authenticate/post" autocomplete="off">
        <input type="hidden" name="username" id="username">

        <textarea  placeholder="Say something!" id="post" name="post" rows="4" cols="50" maxlength="200"></textarea>
        <br><br>
        
        <button type="button"  id="enter" onclick="submitForm()">Post!</button>
    </form>
</div>

Then handle the form submit in JS, while setting a hidden input in the form:

function submitForm()
{
    let name = localStorage.getItem('username');

    // set the value of the hidden input
    document.getElementById("username").value = name;

    // submit the form
    document.getElementById("post-form").submit();
}

OR

You still need the hidden input, but on DOM ready event, you could set the input value:

document.addEventListener('DOMContentLoaded', function() {
    let name = localStorage.getItem('username');

    // set the value of the hidden input
    document.getElementById("username").value = name;
})

This way you can ensure that your "username" will be posted.

  • Related