How to send values from LocalStorage to Flask #app.route()? - javascript

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 class="posting">
<h5>Write Something & Post!</h5>
<form method="POST" action = "/authenticate/post" autocomplete="off">
<textarea class="books" placeholder="Say something!" id="post" name="post" rows="4" cols="50" maxlength="200"></textarea>
<br><br>
<input id="enter" type="submit" class="books" value="Post!" onclick="getname()">
</form>
</div>
The getname() function of my main.js
function getname() {
let name = localStorage.getItem('username');
}

I'd change the submit input to a simple button:
<div class="posting">
<h5>Write Something & Post!</h5>
<form id="post-form" method="POST" action = "/authenticate/post" autocomplete="off">
<input type="hidden" name="username" id="username">
<textarea class="books" placeholder="Say something!" id="post" name="post" rows="4" cols="50" maxlength="200"></textarea>
<br><br>
<button type="button" class="books" 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

Trouble with form.submit() and form.reset()

I am trying to submit a POST request to my flask API using form.submit() and then reset the form using form.reset(). In my javascript code, I am able to do form.submit() and the data is posted to my database successfully, however, if I follow that with form.reset(), the data is NOT added to my database but the form resets. Any idea why I get this?
Flask:
class Signup(db.Model):
__tablename__ = 'signup'
user_id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(200))
flag_1 = db.Column(db.String(1))
flag_2 = db.Column(db.String(1))
def __init__(self, email, flag_1, flag_2):
self.email = email
self.flag_1 = flag_1
self.flag_2 = flag_2
#app.route('/signup', methods=['POST'])
def signup():
if request.method == 'POST':
email = request.form['email']
flag_1 = request.form['flag_1']
flag_2 = request.form['flag_2']
if email == '':
return
if db.session.query(Signup).filter(Signup.email == email).count() == 0:
data = Signup(email, flag_1, flag_2)
db.session.add(data)
db.session.commit()
return
return
HTML:
<form
id="signup-form"
name="signup-form"
action="http://127.0.0.1:5000/signup"
method="post"
>
<label for="email">Email:</label>
<input type="text" id="email" name="email" /><br />
<label for="flag_1"> Flag 1:</label>
<input type="checkbox" name="flag_1" value="Y" /><br />
<input type="hidden" name="flag_1" value="N" />
<label for="flag_2"> Flag 2:</label>
<input type="checkbox" name="flag_2" value="Y" /><br />
<input type="hidden" name="flag_2" value="N" />
<button type="submit" id="signup-btn">Sign me up!</button>
</form>
JavaScript:
document.querySelector("#signup-btn").addEventListener("click", function () {
const signupForm = document.getElementById("signup-form");
signupForm.submit();
signupForm.reset(); // if i have just one of either submit or reset, they work, but if I have both, the form just resets
});
Thanks!
submit() does not submit the form instantly. It sets up a submit to happen when the event loop is free.
The browser keeps running your JS and resets the form.
Then the form submits, but with the default values because you reset it.
Typically, resetting the form at that stage would be pointless even if that wasn't the case. The browser will navigate to the page returned from the form submission, even if contains identical HTML, the rendered form will contain the values specified as default in that HTML.

How to embed form data in the action link?

I have a form defined:
<form method="post">
<label for="phone_or_uid">Enter a phone number or uid:</label>
<input type="text" name="phone_or_uid" value=""></input>
<input type="submit" name="" value="Submit"></input>
</form>
Currently, when this form is submitted I am able to work with the data and add info to the page based on the value of phone_or_uid. However, what I'd like to do is something where the form redirects to the same page but with the value of phone_or_uid appended to the end. So, if the initial page is https://myhost.com/lookup then submitting the form should bring the user to https://myhost.com/lookup/16175431234 if the value of the phone_or_uid input box is 16175431234.
Essentially, my form should then look something like this:
<form action={some code that puts the value of phone_or_uid here}>
...
</form>
Is this possible? And if so, how could I accomplish this? I don't want to create or redirect to any extra files, if possible.
I would use JavaScript. Listen for the submit event and redirect to a custom url.
this is just a really general example:
<form method="post" onsubmit="submitFunction()">
<label for="phone_or_uid">Enter a phone number or uid:</label>
<input type="text" name="phone_or_uid" id="phone_or_uid" value=""></input>
<input type="submit" name="" value="Submit"></input>
</form>
<script>
submitFunction = (event) => {
event.preventDefault();
const phoneInfo = document.getElementById('phone_or_uid').value;
fetch('http://myhost.com/lookup/' + phoneInfo, {
method: 'post'
})
.then(response => {
window.location.href = "http://myhost.com/lookup/' + phoneInfo";
});
}
</script>

How to get a form submit button to save to localStorage

I am a beginner and am trying to figure out how to get this to work. I have a form and I want the submit button to be able to save to the localStorage. So far, this is what I have.
<script>
function storeRecipe() {
localStorage.setItem($("#recipe-name").val(), $("#recipe-
description").val());
console.log(Object.keys(localStorage));
}
</script>
<b>Recipe Name:</b>
<br>
<textarea id="recipe-name" rows="1" cols="35"></textarea>
<br><br>
<b>Recipe Description:</b>
<br>
<textarea id="recipe-description" rows="15" cols="35"></textarea>
<br><br>
<input type="submit" value="Send Recipe" onClick="storeRecipe()">
Upon submit, you can stop the submission of the form and save each input field into as a localStorage key. Working jsfiddle: https://jsfiddle.net/mr4ms4zp/. Open the console cmd+opt+i on macs to see the changed localStorage object.
<form method="POST">
<b>Recipe Name:</b>
<br>
<textarea id="recipe-name" rows="1" cols="35"></textarea>
<br><br>
<b>Recipe Description:</b>
<br>
<textarea id="recipe-description" rows="15" cols="35"></textarea>
<br><br>
<input type="submit" value="Send Recipe">
</form>
<script>
document.querySelector('form').onsubmit = function(e) {
e.preventDefault();
var name = document.querySelector('#recipe-name').value;
var description = document.querySelector('#recipe-description').value;
localStorage["name"] = name;
localStorage["description"] = description;
console.log(localStorage);
}
</script>
Solution with Vanilla Javascript
function storeRecipe() {
let name = document.getElementById("recipe-name").value;
let description = document.getElementById("recipe-description").value
localStorage.setItem(name, description);
}
Avoid the submit default behavior with event.preventDefault() or change the type of the button, i would recommend the second one:
<button type="button" value="Send Recipe" onClick"storeRecipe()">Submit</button>

How to prevent browser from opening a new page on form submit?

There's an email subscription form in a web page, When someone enters his email and clicks on submit button, We don't want this page to be redirected to form action url, We just want it's submit button text value to be converted to another text, something like "Thank You!". How is it possible? Should I go through ajax? or javascript?
Here's the form:
<form class="ml-block-form" action="//app.mailerlite.com/webforms/submit/myownID" data-code="myownID" method="POST" target="_blank">
<div class="form-group ml-field-email ml-validate-required ml-validate-email">
<input class="newsletter-email" type="email" name="fields[email]" placeholder="Email*"/>
</div>
<input type="hidden" name="ml-submit" value="1" />
<p>
<input class="newsletter-submit" type="submit" value="Get Updates!"/>
</p>
For starters remove target="_blank" from your form tag.
Then, within your jQuery, do something along the lines of this:
$(".ml-block-form").submit(function(){
var vals = $(this).serialize();
$.ajax({
url: "postpage.php",
method: "POST",
data: vals,
success: function(data) {
$("#formsubmit").val("Thank you!");
}
});
return false; // prevent from submit
});
I've altered your HTML as well, as it was originally very messy. You can of course add the other elements back if you need:
<form class="ml-block-form" action="" data-code="myownID" method="post">
<input id="mainval" type="email" name="fields[email]" placeholder="Email*">
<input id="hiddenval" name="ml-submit" value="1" />
<input id="formsubmit" type="submit" value="Get Updates!"/>
</form>
You can simply remove target="blank" because blank value opens the linked document in a new window.
Instead of
<input class="newsletter-submit" type="submit" value="Get Updates!"/>
use
<button id="newsletter-submit" value="Get Updates!"/>
(note that I changed class for id)
And then use jQuery to handle the click on the button:
$("#newsletter-submit").click(function () {
$(this).prop("value", "Thank You!");
// do something else with the input values e.g. send them via ajax to a server script
});

Validate html5 form before calling php function?

I currently have a html5 form with a basic text-area inside of it, when you hit the submit button a php script is called that sends the data to the database.
However, before the PHP script is called, I would like to run some validation on the form (checking if it is null etc...) before the PHP is called, preferably in javascript.
Is there a way I can do this?
Thanks.
Html5 form:
<form action="submit.php" method="POST">
<tr>
<td id="textBox-back">
<textarea id="rage-box" type="text" name="rage" cols="40" rows="5" maxlength="160"> </textarea>
<input id="submit" value="" name="submit" type="submit"/>
</td>
</form>
<script language="javascript">
function validate(){
//Code of validation
return false;
}
</script>
<form action="submit.php" method="POST" onsubmit="return validate();">
<tr>
<td id="textBox-back">
<textarea id="rage-box" type="text" name="rage" cols="40" rows="5" maxlength="160"> </textarea>
<input id="submit" value="" name="submit" type="submit"/>
</td>
</form>
You need to add an onclick on your submit or form.
var sub = document.getElementById('submit');
var tex = document.getElementById('rage-box');
sub.onclick = function(e){
if(tex.value == ''){
//stopping it from being sent
e.preventDefault();
alert('make sure everything is filled out');
}
}
If you add the event on your form you need to:
Give an id to your form
Get your form and add the form.onsubmit = function(){};
Then just copy the code inside the anonymous function.

Categories

Resources