get input form not as variable but as url - html

I am building a webservice so people can search into the database. Lets say I have users and companies. Each user and company can be found thought their id. So if you search myurl/users/<id> you get information of that user, on the other hand if you search company/ you get information of that company.
For this I have created two simple input texts (one for users and another for companies) where people can type the <id>. My problem is that when I get the value from the input text I get this myrul/users?<id> and not myurl/users/id. I tried to hardcode the slash but then I get myrul/users/?<id>.
So my question is how can I get input text as a url and not as a variable.
I am using flask so my html has jinja2 code like this:
<!-- USER id -->
<form method='GET' action={{url_for('get_info_by_id', type_collection='user')}}>
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
<!-- COMPANY id-->
<form method='GET' action={{url_for('get_info_by_id', type_collection='company')}}>
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
In my python script (flask)
#app.route('myurl/<type_collection>/<my_id>')
get_info_by_id(type_collection,my_id):
# search into the database and return info about that id

As #dirn suggested in the commentary, I made it through JavaScript, here is the code if someone else is also interested:
HTML:
<!-- USER id -->
<form method='GET' class="search" id="user" action="">
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
<!-- COMPANY id-->
<form method='GET' class="search" id="company" action="">
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
JS:
$(".search").submit(function( event ){
event.preventDefault();
var my_id = $(this).find(":input").val();
url = 'myurl/'+ $(this).attr("id") + '/' + my_id;
window.location.href = url;
});
python (flask)
#app.route('myurl/<type_collection>/<my_id>')
get_info_by_id(type_collection,my_id):
# search into the database and return info about that id

Is there a reason you cannot use the variable, or are you just trying to get it into a URL so that you can do your search? I went out on a limb and assumed you just want the form and database search to work, so try the following out.
Adjust your route like so:
#app.route('myurl/<type_collection>/')
def findAllTheThings():
if not request.form['my_id']: # Just check if a specific entity is chosen
return render_template('YourTemplateHere') # If no entity, then render form
entity_id = request.form['my_id']
get_info_by_id(type_collection, entity_id):
# search into the database and return info about that id
Now adjust the template as follows:
<!-- USER id -->
<form method='GET' action={{url_for('findAllTheThings', type_collection='user')}}>
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
<!-- COMPANY id-->
<form method='GET' action={{url_for('findAllTheThings', type_collection='company')}}>
<input type="text" name="my_id"/><input type="submit" value="Go">
</form>
Now, if no entity has been selected you'll just render the form. You can throw in a flash to let them know they need to select a specific ID, or just let them figure it out. If an entity has been selected, you will call the fucntion correctly.

Related

How to add default values to input fields in Thymeleaf

I am programming in Spring and using Thymeleaf as my view, and am trying to create a form where users can update their profile. I have a profile page which lists the user's information (first name, last name, address, etc), and there is a link which says "edit profile". When that link is clicked it takes them to a form where they can edit their profile. The form consists of text fields that they can input, just like your standard registration form.
Everything works fine, but my question is, when that link is clicked, how do I add the user's information to the input fields so that it is already present, and that they only modify what they want to change instead of having to re-enter all the fields.
This should behave just like a standard "edit profile" page.
Here is a segment of my edit_profile.html page:
First Name:
Here is the view controller method that returns edit_profile.html page:
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEditProfilePage(Model model) {
model.addAttribute("currentUser", currentUser);
System.out.println("current user firstname: " + currentUser.getFirstname());
model.addAttribute("user", new User());
return "edit_profile";
}
currentUser.getFirstname() prints out the expected value, but I'm getting blank input values in the form.
Thanks.
Solved the problem by removing th:field altogether and instead using th:value to store the default value, and html name and id for the model's field. So name and id is acting like th:field.
I'm slightly confused, you're adding currentUser and a new'd user object to the model map.
But, if currentUser is the target object, you'd just do:
<input type="text" name="firstname" value="James" th:value="${currentUser.firstname}" />
From the documentation:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
I did not have a form with input elements but only a button that should call a specific Spring Controller method and submit an ID of an animal in a list (so I had a list of anmials already showing on my page). I struggled some time to figure out how to submit this id in the form. Here is my solution:
So I started having a form with just one input field (that I would change to a hidden field in the end). In this case of course the id would be empty after submitting the form.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
The following did not throw an error but neither did it submit the animalIAlreadyShownOnPage's ID.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
In another post user's recommended the "th:attr" attribute, but it didn't work either.
This finally worked - I simply added the name element ("id" is a String attribute in the Animal POJO).
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" name="id" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>

HTML generate URL from Input

i am working on a search function, herefore i need the value of an input to generate the final url (which shows the results)
Let's say the user enters the content he is looking for here:
Name: <input type="text" id="myText">
now i need to generate a hyperlink from
http://constant/constant?query=NAME&someotherconstantthings
here, the NAME needs to be replaced from the content of the input
Try to use PHP, you could add a action to the Form Element to post the entered informations to the PHP file, then generate ur hyperlink.
<form action="phpfilename.php" method="post">
Name: <input type="text" id="myText" name="myText">
<input type="submit" value="Search">
</form>
<?php
$name = $_POST['myText'];
$hyperlink = 'http://constant/constant?query='.$name;
?>
You need something like this:
<form action="URL" method="get">
Enter your name here: <input type="text" name="query" value="">
<input type="submit" value="Search">
</form>
You need to replace the keyword URL with the path to the page which performs the search. You can remove the keyword URL if want to submit the form to the same page.

append string parmeters while submitting a GET form from HTML

Consider a form in Html:
<form action="demo_form.asp" method="get">
<div class="form-group" style="margin-top:7px;">
<label class=".... </label>
<input type="text" name="prefersite1" placeholder="http://www.website.com">
<input type="text" name="prefersite2" cla....;">
<input type="text" name="prefersite3" cl....">
<input type="text" name="prefersite4" c....">
<input type="text" name="prefersite5" cla....">
</div>
On using a 'submit' type button, is there a way to get appended prefersite_list[] or comma separated string in the url
The button I used is just:
<button type="submit">
Submit
</button>
I am working on django platform and use this url to extract variables by request.GET.get method in python. Is there a way to change name=prefersite[0], [1] etc so that I will get a single long string.
Instead of /?prefersite1=&prefersite2=&prefersite3=.. , I need a single /?prefersite=.
Using prefersite[] as name seems to be working for post forms, but I need to use get forms.

HTML Form element to URL

I am using an eCommerce engine script that uses a different search method.
Instead of a URL using GET like this:
http://search.com/searchc?q=the+query
It uses
http://search.com/searchc/the+query
How can I make a form to POST or GET to that, because this form makes the URL
http://search.com/searchc/?q=the+query
<form action="/searchc/" method="post">
<input type="text" id="q" name="q">
<input type="submit" value="go">
</form>
Also tried this (get or post do not work for both of these)
<form action="/searchc/" method="post">
<input type="text" id="" name="">
<input type="submit" value="go">
</form>
The reliable way has two components: Client-side JavaScript manipulation, which turns form submission to a request as needed, and (as backup for non-JS situations) a simple server-side redirect utility which receives a request from the form and redirects it as modified.
Something like this (for the GET case):
<form action="http://www.example.com/redirect"
onsubmit="location.href = document.getElementById('f1').value +
document.getElementById('q').value; return false">
<input type="text" id="q" name="f2">
<input type="submit" value="go">
<input type=hidden id=f1 name=f1 value="http://search.com/search/">
</form>
Here http://www.example.com/redirect is some server-side form handler that just reads the form fields and picks up fields named f1, f2,..., concatenates them into a single string, and redirects using it as a URL. As a CGI script, this would be
use CGI qw(:standard);
$dest = '';
$i = 1;
while(param('f'.$i)) {
$dest .= param('f'.$i++); }
print "Location: $dest\n\n";
<form action="/searchc/" method="post" onsubmit="this.action+=this.q.value;return true">
<input type="text" id="q">
<input type="submit" value="go">
</form>
spaces will be submited as %20
you can use
this.action+=this.q.value.split(' ').join('+')
to replace them
This is very strange url pattern, but anyway you could do something like:
$(function () {
$('form').submit(function () {
var url = '/searchc/' + encodeURIComponent($(this).find('[name=q]').val());
window.location = url;
return false;
});
});

Two submit buttons in one form

I have two submit buttons in a form. How do I determine which one was hit serverside?
Solution 1:
Give each input a different value and keep the same name:
<input type="submit" name="action" value="Update" />
<input type="submit" name="action" value="Delete" />
Then in the code check to see which was triggered:
if ($_POST['action'] == 'Update') {
//action for update here
} else if ($_POST['action'] == 'Delete') {
//action for delete
} else {
//invalid action!
}
The problem with that is you tie your logic to the user-visible text within the input.
Solution 2:
Give each one a unique name and check the $_POST for the existence of that input:
<input type="submit" name="update_button" value="Update" />
<input type="submit" name="delete_button" value="Delete" />
And in the code:
if (isset($_POST['update_button'])) {
//update action
} else if (isset($_POST['delete_button'])) {
//delete action
} else {
//no button pressed
}
If you give each one a name, the clicked one will be sent through as any other input.
<input type="submit" name="button_1" value="Click me">
There’s a new HTML5 approach to this, the formaction attribute:
<button type="submit" formaction="/action_one">First action</button>
<button type="submit" formaction="/action_two">Second action</button>
Apparently this does not work in Internet Explorer 9 and earlier, but for other browsers you should be fine (see: w3schools.com HTML <button> formaction Attribute).
Personally, I generally use JavaScript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are Internet Explorer before version 9 with JavaScript disabled.
Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.
As noted by Pascal_dher in the comments, this attribute is also available on the <input> tag as well.
An even better solution consists of using button tags to submit the form:
<form>
...
<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="delete">Delete</button>
</form>
The HTML inside the button (e.g. ..>Update<.. is what is seen by the user; because there is HTML provided, the value is not user-visible; it is only sent to server. This way there is no inconvenience with internationalization and multiple display languages (in the former solution, the label of the button is also the value sent to the server).
This is extremely easy to test:
<form action="" method="get">
<input type="submit" name="sb" value="One">
<input type="submit" name="sb" value="Two">
<input type="submit" name="sb" value="Three">
</form>
Just put that in an HTML page, click the buttons, and look at the URL.
Use the formaction HTML attribute (5th line):
<form action="/action_page.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<button type="submit">Submit</button><br>
<button type="submit" formaction="/action_page2.php">Submit to another page</button>
</form>
<form>
<input type="submit" value="Submit to a" formaction="/submit/a">
<input type="submit" value="submit to b" formaction="/submit/b">
</form>
The best way to deal with multiple submit buttons is using a switch case in the server script
<form action="demo_form.php" method="get">
Choose your favorite subject:
<button name="subject" type="submit" value="html">HTML</button>
<button name="subject" type="submit" value="css">CSS</button>
<button name="subject" type="submit" value="javascript">JavaScript</button>
<button name="subject" type="submit" value="jquery">jQuery</button>
</form>
Server code/server script - where you are submitting the form:
File demo_form.php
<?php
switch($_REQUEST['subject']) {
case 'html': // Action for HTML here
break;
case 'css': // Action for CSS here
break;
case 'javascript': // Action for JavaScript here
break;
case 'jquery': // Action for jQuery here
break;
}
?>
Source: W3Schools.com
Maybe the suggested solutions here worked in 2009, but I’ve tested all of this upvoted answers and nobody is working in any browsers.
The only solution I found working was this (but it's a bit ugly to use I think):
<form method="post" name="form">
<input type="submit" value="dosomething" onclick="javascript: form.action='actionurl1';"/>
<input type="submit" value="dosomethingelse" onclick="javascript: form.action='actionurl2';"/>
</form>
You formaction for multiple submit buttons in one form
example:
<input type="submit" name="" class="btn action_bg btn-sm loadGif" value="Add Address" title="" formaction="/addAddress">
<input type="submit" name="" class="btn action_bg btn-sm loadGif" value="update Address" title="" formaction="/updateAddress">
An HTML example to send a different form action on different button clicks:
<form action="/login" method="POST">
<input type="text" name="username" value="your_username" />
<input type="password" name="password" value="your_password" />
<button type="submit">Login</button>
<button type="submit" formaction="/users" formmethod="POST">Add User</button>
</form>
The same form is being used to add a new user and login user.
Define name as array.
<form action='' method=POST>
(...) some input fields (...)
<input type=submit name=submit[save] value=Save>
<input type=submit name=submit[delete] value=Delete>
</form>
Example server code (PHP):
if (isset($_POST["submit"])) {
$sub = $_POST["submit"];
if (isset($sub["save"])) {
// Save something;
} elseif (isset($sub["delete"])) {
// Delete something
}
}
elseif very important, because both will be parsed if not.
Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for Python, using CherryPy (although it may be useful for other contexts, too):
<button type="submit" name="register">Create a new account</button>
<button type="submit" name="login">Log into your account</button>
Rather than using the value to determine which button was pressed, you can use the name (with the <button> tag instead of <input>). That way, if your buttons happen to have the same text, it won't cause problems. The names of all form items, including buttons, are sent as part of the URL.
In CherryPy, each of those is an argument for a method that does the server-side code. So, if your method just has **kwargs for its parameter list (instead of tediously typing out every single name of each form item) then you can check to see which button was pressed like this:
if "register" in kwargs:
pass # Do the register code
elif "login" in kwargs:
pass # Do the login code
<form method="post">
<input type="hidden" name="id" value="'.$id.'" readonly="readonly"/>'; // Any value to post PHP
<input type='submit' name='update' value='update' formAction='updateCars.php'/>
<input type='submit' name='delete' value='delete' formAction='sqlDelete.php'/>
</form>
I think you should be able to read the name/value in your GET array. I think that the button that wasn't clicked won't appear in that list.
You can also do it like this (I think it's very convenient if you have N inputs).
<input type="submit" name="row[456]" value="something">
<input type="submit" name="row[123]" value="something">
<input type="submit" name="row[789]" value="something">
A common use case would be using different ids from a database for each button, so you could later know in the server which row was clicked.
In the server side (PHP in this example) you can read "row" as an array to get the id.
$_POST['row'] will be an array with just one element, in the form [ id => value ] (for example: [ '123' => 'something' ]).
So, in order to get the clicked id, you do:
$index = key($_POST['row']);
key
As a note, if you have multiple submit buttons and you hit return (ENTER key), on the keyboard the default button value would be of the first button on the DOM.
Example:
<form>
<input type="text" name="foo" value="bar">
<button type="submit" name="operation" value="val-1">Operation #1</button>
<button type="submit" name="operation" value="val-2">Operation #2</button>
</form>
If you hit ENTER on this form, the following parameters will be sent:
foo=bar&operation=val-1
The updated answer is to use the button with formaction and formtarget
In this example, the first button launches a different url /preview in a new tab. The other three use the action specified in the form tag.
<button type='submit' class='large' id='btnpreview' name='btnsubmit' value='Preview' formaction='/preview' formtarget='blank' >Preview</button>
<button type='submit' class='large' id='btnsave' name='btnsubmit' value='Save' >Save</button>
<button type='submit' class='large' id='btnreset' name='btnsubmit' value='Reset' >Reset</button>
<button type='submit' class='large' id='btncancel' name='btnsubmit' value='Cancel' >Cancel</button>
Full documentation is here
In HTML5, you can use formaction & formmethod attributes in the input field
<form action="/addimage" method="POST">
<button>Add image</button>
<button formaction="/home" formmethod="get">Cancel</button>
<button formaction="/logout" formmethod="post">Logout</button>
</form>
You can also use a href attribute and send a get with the value appended for each button. But the form wouldn't be required then
href="/SubmitForm?action=delete"
href="/SubmitForm?action=save"
You can present the buttons like this:
<input type="submit" name="typeBtn" value="BUY">
<input type="submit" name="typeBtn" value="SELL">
And then in the code you can get the value using:
if request.method == 'POST':
#valUnits = request.POST.get('unitsInput','')
#valPrice = request.POST.get('priceInput','')
valType = request.POST.get('typeBtn','')
(valUnits and valPrice are some other values I extract from the form that I left in for illustration)
Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for PHP
<?php
if(isset($_POST["loginForm"]))
{
print_r ($_POST); // FOR Showing POST DATA
}
elseif(isset($_POST["registrationForm"]))
{
print_r ($_POST);
}
elseif(isset($_POST["saveForm"]))
{
print_r ($_POST);
}
else{
}
?>
<html>
<head>
</head>
<body>
<fieldset>
<legend>FORM-1 with 2 buttons</legend>
<form method="post" >
<input type="text" name="loginname" value ="ABC" >
<!--Always use type="password" for password -->
<input type="text" name="loginpassword" value ="abc123" >
<input type="submit" name="loginForm" value="Login"><!--SUBMIT Button 1 -->
<input type="submit" name="saveForm" value="Save"> <!--SUBMIT Button 2 -->
</form>
</fieldset>
<fieldset>
<legend>FORM-2 with 1 button</legend>
<form method="post" >
<input type="text" name="registrationname" value ="XYZ" >
<!--Always use type="password" for password -->
<input type="text" name="registrationpassword" value ="xyz123" >
<input type="submit" name="registrationForm" value="Register"> <!--SUBMIT Button 3 -->
</form>
</fieldset>
</body>
</html>
Forms
When click on Login -> loginForm
When click on Save -> saveForm
When click on Register -> registrationForm
Simple. You can change the action of form on different submit buttons click.
Try this in document.Ready:
$(".acceptOffer").click(function () {
$("form").attr("action", "/Managers/SubdomainTransactions");
});
$(".declineOffer").click(function () {
$("form").attr("action", "/Sales/SubdomainTransactions");
});