werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'id' - rest

html page
{%block title%}Login page{% endblock %}
{%block content%}
<form action = '#' method="post">
<p>creds:</p>
<p><input type="number" placeholder="id" Id="id" /></p>
<p><input type="text" placeholder="nm" name="nm" /></p>
<p><input type="submit" value="submit" /></p>
</form>
{%endblock%}
app code
#app.route("/")
def home():
return render_template("login.html")
#app.route("/",methods = ["POST","GET"])
def post():
if request.method == "POST":
user = request.form['nm']
id = request.form['id']
sql = ('''INSERT INTO abc
(id, name) VALUES (?, ?)
''')
val = (id,user)
cur.execute (sql, val)
return 'Ok'
i tried using return.form.get('id') but its returning null
Can anyone please help me on this
Thanks

<p><input type="number" placeholder="id" name="id" /></p>
you have typed Id instead of name

When you use request.form["something"] you assume that this something always be part of your request, I recommend you to use request.form.get("something", False) to avoid that error. I hope this will solve your doubts.

I had exactly the same problem, but mine was with a "SelectField" , the update fields would be "None" and to avoid that I just added option value None as shown below:
<option value="None">None</option>
This fixed my problem

Related

GET form in Scala templates

I'm attempting to create a form using GET to search given some input:
<form class="form-inline" role="form" method="get" action="#routes.Index.search">
<div class="form-group">
<label for="search-field">Search:</label>
<input id="search-field" class="form-control" type="text" name="q" placeholder="Sun"/> </div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
Where the Index controller has the following method:
def search(q: String) = Action.async {
...
}
And my routes file has the following route:
GET /search controllers.Index.search(q: String)
I was expecting that this should work as I expect, which is that a GET request should be made to http://foo.bar/search?q=hello if the value in search-field was hello. Instead I get the following compilation error:
/index.scala.html:8: missing arguments for method search in class ReverseIndex;
follow this method with `_' if you want to treat it as a partially applied function
<form class="form-inline" role="form" method="get" action="#routes.Index.search">
Any help with why this is wrong would be much appreciated.
The problem was that I was not providing default values for the query parameters in the routes file:
GET /search controllers.Index.search(q: String ?= "")
fixed the problem.

Passing Text into URL from a Form

I'm trying to insert a variable collected from a form into a URL, but I don't want the "?variable=value" part of the URL.
<form action="http://www.example.com/<?php echo htmlspecialchars($_GET['entry']);?>/" method="GET">
<input type="text" value="" name="entry" id="entry">
<input type='submit'>
</form>
Is there any easy way to do this? I want the browser to go to the following URL when the user types "whatever"
http://www.example.com/whatever/
Edit:
I've changed the code to the following, which seems to work, but have I now introduced a script vulnerability?
<form onSubmit=" location.href = 'https://www.example.com/' + document.getElementById('entry').value + '/' ; return false; ">
<input type="text" value="" name="entry" id="entry" placeholder="Your Promo Code">
<input name="promoSubmit" type="submit" value="Buy Now">
</form>
you could use javascript for this kind of tasks, i don't see why would you involve server side for such thing
but the easiest answer will be like:
<script>
function go(){
window.location='http://www.example.com/'+document.getElementById('url').value;
}
</script>
<input type='text' id='url'>
<button id='btn_go' onclick='javascript:go();'>Go</button>

.asp validate_form wrong somehow?

I've got a little problems with my "contact us" form, whenever i submit it i get the error message 500. IE tells me it's a error at line 62, and that validate_form is not specified.
My code goes like this:.
<form method="POST" action="/cgi-bin/emailer.asp" onsubmit="return validate_form(this); ">
I really don't know anything about .asp, .php, .js etc. so some help would really be needed.
Thanks
-Niko
Update:
function validate_Form(form)
{
var x=document.forms["yhteys"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Sähköposti osoite ei ole oikein.");
return false;
}
}
that's how the code looks right now, but it still isn't working.
<form name="yhteys" method="POST" action="/cgi-bin/emailer.asp" onsubmit="return validate_form(this);">
<div style="float:left;">
Aihe:<b>*</b><br>
<select name="Aihe" required="required" id="Aihe">
<option value="Yhteydenotto">Yhteydenotto</option>
<option value="Arviokäynti">Arviokäynti</option>
<option value="Esitetilaus">Esitetilaus</option>
<option value="Esittelyajan varaus">Esittelyajan varaus</option>
<option value="Palaute">Palaute</option>
<option value="Muu viesti">Muu viesti</option>
</select><br><br>
Nimi:<b>*</b><br>
<input type="text" required="required" name="nimi" size="35"><br><br>
Osoite:<b>*</b><br>
<input type="text" required="required" name="osoite" size="35"><br><br>
Puhelin:<b>*</b><br>
<input type="text" required="required" name="puh" size="35"><br><br>
Sähköposti:<b>*</b><br>
<input type="text" required="required" name="email" size="35"><br><br>
Viesti:<b>*</b><br>
<textarea rows="5" name="viesti" cols="45" required="required" id="Viesti"></textarea>
<div style=" margin-right: 2px; margin-top: 2px;"><input type="submit" value="Lähetä" name="B1"></div><br />
<p>Tähdellä merkityt kohdat ovat pakollisia.</p>
</form>
</div>
There is the whole form section, just so you could tell me more specifically what's wrong.
validate_form(this) is a call to a JavaScript function you have to define.
it might look something like this:
function validate_form(form){
if (form.fieldname.value /* fulfills some condition */)
{
//this will abort the submit
return false;
}
//will only get called when the if-statement does not return true
//this allows the submit to procede
return true;
};
alternatively you can declare a function like this:
var validate_form = function(form){/*your code here*/};
you should put that block of code in the <head>-section of your page inside of:
<script type="text/javascript" >
// your code
</script>
EDIT:
As of your javascript:
If you send this to your function, you do not have to crawl DOM to get your elements.
--> to get any field in your form (which you pass to function with this-Keyword) you can do the following:
form.fieldname
this allows you to access your email like that:
var email = form.email.value;
You can now check your email with a custom-validation, but i recommend using a freely available regex to check it. you can find a nice one in the answer no.3 here
if (!isValid(email)){ //if the given email is not Valid by the function you call
alert("Sähköposti osoite ei ole oikein.");
return false;
}

send html form via post to webservice

I'm very very new on HTML5 development and this question could be very silly but I've found an answer for it (or I've searched very well).
I want to send a form to a web service via post (I don't want to show all fields in URL).
I have two question:
How must I named forms fields? If I trying to send an userName I think I have to put this test as ID to the field which will held that value.
And this is because I'm so curious. Which is the post message content which is sent to web service?
This is an example that I've found searching Internet:
<FORM action="http://somesite.com/prog/adduser" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="email">email: </LABEL>
<INPUT type="text" id="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM
I think I will need those ids to get those values while processing them on web service, isn't it?
It depends, you could do a post to a page with a redirect (in .NET you would handle it this way):
<form action="http://myurl/postpage.ashx" method="post">
<input name="forename" />
<input name="surname" />
<input type="submit" value="Submit" />
</form>
And then pick this up in the server side script at postpage.ashx using:
string forename = Request["forename"];
string surname = Request["surname"];
You could also use jQuery to make an ajax call to the same page using the following:
var forename = $("input[name=\"forename\"]").val();
var surname = $("input[name=\"surname\"]").val();
$.ajax({
url: "http://myurl/postpage.ashx",
type: "POST",
async: true, // set to false if you don't mind the page pausing while waiting for response
cache: false,
dataType: "json",
data: "{ 'forename': '" + forename + "', 'surname': '" + surname + "' }",
contentType: "application/json; charset=utf-8",
success: function(data) {
// handle your successful response here
},
error: function(xhr, ajaxOptions, thrownError) {
// handle your fail response here
}
});
You would handle the post in the server side code the same way. The key thing to note here is that whatever you enter as the name attribute of your input element is what will get POSTed as a key/value pair to your receiving URL.
every web service should give you something like WSDL which normally contains specification of available fields and methods you can use. if the webservice you are connecting to have url webservice.com than try webservice.com/wsdl to get the WSDL.
Check this topic: click
Attribute "name" is the one that needs to be unique in order to pass that parameter to a Servlet (or wherever). The post method then encrypts the message and sends it to the Servlet.
<form method="post" action = "LoginServlet">
Name: <input type="text" name="userName">
Password: <input type="password" name="password">
<input type="submit" name = "Login" class="button">
</form>
In order to access that data you will do something like this in the Servlet:
String userName = request.getParameter("userName");

JSP - check form submission

Let say I have a simple form with no required fields:
<form action="index.jsp" method="post">
<input type="text" name="firstName" />
<input type="text" name="lastName" />
<input type="text" name="email" />
<input type="submit" value="submit" />
</form>
I want to check if the form was submitted by checking the submit parameter (because it's always present). In PHP I can do a simple
if ( $_POST['submit'] )
but the request.getParameter("submit") doesn't seem to work.
So what's the best way to check if a form was submitted?
You need to give the input element a name. It's the element's name which get sent as request parameter name.
<input type="submit" name="submit" value="submit" />
Then you can check it as follows:
if (request.getParameter("submit") != null) {
// ...
}
You perhaps also want to check if "POST".equalsIgnoreCase(request.getMethod()) is also true.
if ("POST".equalsIgnoreCase(request.getMethod()) && request.getParameter("submit") != null) {
// ...
}
Better, however, would be to use a servlet and do the job in doPost() method.
You can try this way:-
if ("POST".equalsIgnoreCase(request.getMethod())) {
// Form was submitted.
} else {
// It may be a GET request.
}