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.
Related
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.
Want to change submit button color after email verification and checkbox marked. Added listeners on changes and they work well. But have no idea how to find out when this events are going to happen to launch function what is going to change submit button color.
```
https://jsfiddle.net/nvologdins/brfj2xk1/
```
Here is a basic example of how to do this.
I also changed the logic a bit to update the values if the user changes them again. - #Ultimater mentioned this also.
function setupButton() {
if (validEmail && validCheckbox) {
// add/show/enable submit button or simply change the color
button.style.color = "red";
} else {
// remove/hide/disable submit button revert the changes
button.style.color = "";
}
}
form.input.addEventListener('input', (event)=>{
validEmail = emailRegex.test(event.target.value);
setupButton();
})
form.checkbox.addEventListener('change', (event)=>{
validCheckbox = event.target.checked;
setupButton();
})
I would also suggest a different method to validate the form using the Constraint Validation API.
Every element has a validity check which can easily be accessed on the form element using formElement.checkValidity() and returns true/false if all (required) fields inside the form are filled with valid values.
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required>
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>
Using this, the browser for itself checks the values if they contain a valid value.
An input[type=email] with required flag must contain a valid mail address.
A checkbox with required flag, must be checked.
An input with required and a pattern must contain a value matching the regular expression from the pattern-attribute.
No need to create extra variables and listen on two form elements separately... You can check the whole thing and update accordingly only by listening to the form element
let form = document.querySelector('form');
let input = document.getElementById('input');
let checkbox = document.getElementById('checkbox');
let submit = document.getElementById('button');
const emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
form.addEventListener('change', (event) => {
if (checkbox.checked && emailRegex.test(input.value)) {
submit.style.color = "red";
} else {
submit.style.color = "black"
}
})
//Update
input.addEventListener('input', () => {
const changeEvent = new Event('change');
form.dispatchEvent(changeEvent)
})
<form class="main__emailAndTerms emailAndTerms">
<div class="emailAndTerms__email">
<input type="text" id="input" placeholder="Type your email address here...">
<label class="emailAndTerms__terms">I agree to <span class="terms__link">terms of service</span>
<input type="checkbox" class="terms__checkbox" id="checkbox">
<span class="terms__checkbox_custom"></span>
</label>
<button type="submit" class="email__submitButton" id="button">Submit</button>
</div>
</form>
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>
On click of search button in my form, i want to set some param to url and submit it.
Below is my javascript
function validateSubmitSearch(form) {
if(form.elements["iAccept"].checked == true) {
form.query.value=form.search_query.value;
form.action = "vendor/search";
form.method = "GET";
form.submit();
}
}
This javascript is returning url as
http://localhost:8080/Project/vendor/search?query=xxx&search_query=xxx&search=Search
Instead i need it as
http://localhost:8080/Project/vendor/search?query=xxx
How this can be done ?
EDIT:
I cannot remove form elements search_query and search
Here is HTML code
<form class="searchform" onSubmit="validateSubmitSearch(this)">
<input name="query" type="hidden" />
<input name="search_query" class="textbox" type="text" />
<input type="checkbox" id="iAccept" name="iAccept" value="I ACCEPT">
<input name="search" class="button" value="Search" type="submit" /></td>
</form>
When you submit a form with `method="GET", all the input fields in the form will be included as URL parameters. If you want some of them to be left out, you need to remove those inputs from the form.
function validateSubmitSearch(form){
if(form.elements["iAccept"].checked == true)
{
form.query.value=form.search_query.value;
form.action = "vendor/search";
form.method = "GET";
form.seach_query.parentNode.removeChild(form.search_query);
form.search.parentNode.removeChild(form.search);
form.submit();
}
}
}
Also, you should disable the default form submission by returning false from the onsubmit code.
<form class="searchform" onsubmit="validateSubmitSearch(this); return false;">
i am creating login web app using ajax and PHP and i use javascript an php to validate the input and it works for the login form,but i added a link under the form if not signed up before the link under form
and the HTML for it is :
don't have account on tobe?
and the signUpForm() function contain
function signUpForm(){
$(".logInForm").load("SignUpForm.html");
}
and it works the content change
but when i use JS to validate input using code (just like the login code witch is working) :
HTML(the input in the SignUpForm.html calls the signUp() function)
<input type="button" value="Sign Up" onclick="signUp()">
function signUp(){
if($("input[class='user']").val()==""|| $("input[class='pass']").val()==""){
$(".error-message").fadeIn();
document.getElementById("error-message").innerHTML="Please fill all fields";
} else{
//action(2) including the php file loading
}
}
what happen is javascript ignores the new input fields and consider that the are deleted and always go to action(2) how can i make js see the new form html?
Assuming I understand your problem correctly, I think this code should help you get on the right footing (http://codepen.io/trevorhreed/pen/bppxRG?editors=1010).
In this example, I'm using $(...).html(...) instead of $(...).load(...) since I don't have a server hosting HTML files, but it should work fine to swap .html(...) out for .load(...).
console.clear();
$(function(){
var placeholder = $('#placeholder'),
signInTpl = $('#signin').html(),
signUpTpl = $('#signup').html();
function goToSignIn(){
placeholder.html(signInTpl);
// or placeholder.load('signin.html');
var btnSignIn = $('#btnSignIn'),
signInUsername = $('#signinUsername'),
signInPassword = $('#signinPassword');
btnSignIn.on('click', function(){
if(signInUsername.val() == '' || signInPassword.val() == ''){
alert('Sign In form is NOT valid');
}else{
alert('Sign In form is valid');
}
})
}
function goToSignUp(){
placeholder.html(signUpTpl);
// or placeholder.load('signup.html');
var btnSignUp = $('#btnSignUp'),
signUpUsername = $('#signupUsername'),
signUpPassword = $('#signupPassword');
btnSignUp.on('click', function(){
if(signUpUsername.val() == '' || signUpPassword.val() == ''){
alert('Sign Up form is NOT valid');
}else{
alert('Sign Up form is valid');
}
})
}
goToSignIn();
$('#btnGoToSignUp').on('click', function(){
goToSignUp();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="placeholder"></div>
<template id="signin">
<h2>Sign In</h2>
<form method="post">
<label>
Username
<input id="signinUsername" />
</label>
<label>
Password
<input id="signinPassword" />
</label>
Sign Up
<button type="button" id="btnSignIn">Sign In</button>
</form>
</template>
<template id="signup">
<h2>Sign Up</h2>
<form method="post">
<label>
Username
<input id="signupUsername" />
</label>
<label>
Password
<input id="signupPassword" />
</label>
<button type="button" id="btnSignUp">Sign In</button>
</form>
</template>