send html form via post to webservice - forms

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");

Related

Form not submitting with query parameters set with "asp-route" despite being in action

UPDATE: per this response this is behavior of HTML5? I tried setting the parameters in hidden inputs and that works. Doesn't make much sense to me, but what do I know.
I have my form for a "next page" button set up like this:
<form id="next" method="get"
asp-controller="Search"
asp-action="Cities"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
asp-route-pageNumber="#(Model.PageIndex + 1)">
<input form="next" type="submit" class="page-btn" disabled="#nextDisabled" value="Next" />
</form>
When I inspect the page, the form has the correct action url (example):
/Search/Cities?currentFilter=Test&pageNumber=2
But the request actually being made is to
/Search/Cities?
But when it hits the controller, all of the parameters are null. Here is the top of my controller:
[Route("Search/Cities")]
public ActionResult Cities(string SearchString, string sortOrder, string currentFilter, int? pageNumber)
I'm not sure what I'm missing here.
you have 3 choices. This code was tested
first the most popular, you have to use post
<form id="next" method="post"
asp-controller="home"
asp-action="test"
asp-route-sortOrder="CurrentSort"
asp-route-currentFilter="CurrentFilter"
asp-route-pageNumber="1">
<label for="searchString">Search</label>
<input type="text" id="searchString" name="searchString"><br><br>
<input form="next" type="submit" class="page-btn" value="Next" />
</form>
in this case searchingString will be sent in a request body, all another params in a query string
second
<a href="/Home/Test?sortOrder=CurrentSort&currentFilter=CurrentFilter&pageNumber=2">
<button class="page-btn">Next</button>
</a>
the second option will generate get request if it is so important for you, but you will not be able post search string except using ajax.
third, you can use get, but route params should be in the inputs, probably hidden, search string will have a visible input
<form id="next" method="get"
asp-controller="home"
asp-action="test">
<input type="hidden" id="sortOrder" name="sortOrder" value="CurrentSort" />
<input type="hidden" id="currentFilter" name="currentFilter" value="CurrentFilter" />
<input type="hidden" id="pageNumber" name="pageNumber" value="23" />
<label for="searchString">Search</label>
<input type="text" id="searchString" name="searchString"><br><br>
<input form="next" type="submit" class="page-btn" value="Next" />
</form>
in this case nothing will be inside of the body, everything in a query string including searchString.

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>

Angular JS: sending form field data in a PUT request (like POST does)

I'm trying to write a client that does all four REST verbs (GET/POST/PUT/DELETE) and have gotten all but the PUT done. The REST/CRUD API I'm working from wants to update an entry by calling PUT /realmen/ID-string and including the key-value pairs as JSON. For a POST this seems to work "automatically", but not for a PUT.
My HTML looks like:
<div id="list">
<form novalidate class="edit-form">
<p>Title <input ng-model="realmen.title" type="text" value="{{realmen.title}}" /></p>
<p>Real Men <input ng-model="realmen.realmen" type="text" value="{{realmen.realmen}}" /> </p>
<p>Real Role-Players <input ng-model="realmen.realroleplayers" type="text" value="realmen.realroleplayers}}" /></p>
<p>Loonies <input ng-model="realmen.loonies" type="text" value="{{realmen.loonies}}" /></p>
<p>Munchkins <input ng-model="realmen.munchkins" type="text" value="{{realmen.munchkins}}" /></p>
<input ng-model="realmen.entryId" type="hidden" value="{{entryId}}"/>
<button ng-click="change()">UPDATE ({{entryId}})"</button></p>
</form>
</div>
My controller looks like:
$scope.realmen = RealMen.get({entryId: $routeParams.entryId}, function() {
$scope.master = angular.copy($scope.realmen); // For resetting the form
});
$scope.change = function() {
console.log($scope.realmen);
RealMen.update({entryId: $scope.entryId}, function() {
$location.path('/');
});
}
And finally, my services look like:
angular.module('realmenServices', ['ngResource']).
factory('RealMen', function($resource){
var RealMen = $resource(
'http://localhost\\:3000/realmen/:entryId',
{},
{
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method: 'PUT', params:{entryId:'#entryId'}},
remove: {method:'DELETE'}
});
return RealMen;
});
The PUT is getting called with the correct id value in the URL, but the Request Payload only contains the entryId, so the backend API gets no expected keys and values and essentially blanks out the record in the database.
The console.log($scope.realmen) does show the form fields, along with a lot of extra data. I tried calling RealMen.update($scope.realmen, ...) (similarly to calling .save()), but all those extra fields are tacked on as query string parameters to the URL in a spectacularly ugly fashion.
Because your $scope.realmen is a resource instance, instead of using RealMen.update, you can just call $scope.realmen.$update() (note that there is a "$"). The instance action method will take care of sending the data for you.

Login Form For Http Basic Auth

I am running a Perl application named bitlfu.For login it is using something like Apache HTTP Basic Auth but not a form.I want to make form for the login with username and password field.
I have tried JavaScript and PHP with no results till now.
So I need help!
PS:
this kind of url works
http://user:password#host.com
I think a simple JavaScript like:
document.location='http://' + user + ':' + pass + '#mydomain.tld';
should do the work.
So basically, you have to create a form, with a user and pass field, then onsubmit, use the part of JavaScript given here:
<form method="post" onsubmit="javascript:document.location='http://' + $('login') + ':' + $('pass') + '#mydomain.tld';">
<input type="text" name="login" id="login" />
<input type="password" name="pass" id="pass" />
<input type="submit" value="ok"/>
</form>
where $() is a document.getElementById or jquery or so. I used the $() function to make the code shorter. Here is an implementation, which does not work on every browser. Again, look throw jQuery for cross browser solution.
function $(_id) { return document.getElementById(_id); }
Otherwise, you can use php and redirect the user with a header location.
php way:
<?php
if (isset($_POST['login']) && isset($_POST['password'])) { header('Location: ' . urlencode($_POST['login']) . ':' . urlencode($_POST['password']) . '#domain.tld'); }
else
{
?>
<form method="post" onsubmit="javascript:document.location='http://' + $('login') + ':' + $('pass') + '#mydomain.tld';">
<input type="text" name="login" id="login" />
<input type="password" name="pass" id="pass" />
<input type="submit" value="ok"/>
</form>
<?php
}
You can redirect the user to http://user:password#host.com with Perl, or using JavaScript. I don't know Perl so I'll show you the JS:
function submitted() {
document.location = "http://" + document.getElementById("username").value + ":" + document.getElementById("password").value + "#host.com";
}
<form onSubmit="submitted">...blablabla...</form>
This should work. The only problem is that this shows the password in the URL.
The awesome AJAX way using jQuery:
$.ajax({
'url': 'http://host.com/',
//'otherSettings': 'othervalues',
username: $("username").val(),
password: $("password").val()
},
sucess: function(result) {
alert('done');
}
});
The ultimate Perl way (I think)
$username = # somehow get username
$password = # somehow get password
use CGI;
my $query=new CGI;
print $query->redirect('http://host.com/');
The method of explicitly redirecting document.location with username#password in URL caused me some problems with Safari giving a phishing warning.
If I instead first make an AJAX request to a URL with basic auth headers added, and then redirect document.location without the username/pass in the URL then it worked better for me
Example
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('form').submit(function() {
$.ajax({
url: 'https://site/collaborators/',
username: $("#login").val(),
password: $("#pass").val()
}).done(function() {
$("#error_msg").html("");
document.location='https://site/collaborators/';
}).fail(function(result) {
console.error(result);
$("#error_msg").html("Error logging in: "+result.statusText);
});
return false;
});
});
</script>
<div id="error_msg" style="color: red"></div>
<form method="post">
Username:
<input type="text" name="login" id="login" />
Password:
<input type="password" name="pass" id="pass" />
<input type="submit" value="Submit"/>
</form>
Unfortunate caveat with Safari only, if you type your username and password incorrectly, then it makes another standard HTTP basic auth popup, but this is better than a big red "Phishing warning" that occurs when you make the document.location include username/pass
Chrome doesn't have duplicate popup if login credentials are incorrect though
This is a simple plug&play solution ;-). Will work for any domain (and on HTTPS too):
<script>
function submitAuthForm() {
var login = document.getElementById('login').value;
var pass = document.getElementById('pass').value;
location = location.href.replace('://', '://' + encodeURIComponent(login) + ':' + encodeURIComponent(pass) + '#');
// might be required to reload on Firefox (FF shows confirmation dialog)
setTimeout(function(){
location.reload(true);
}, 5000);
}
</script>
<form method="get" onsubmit="submitAuthForm(); return false">
<input type="text" id="login" />
<input type="password" id="pass" />
<input type="submit" value="OK" />
</form>
You can drop this in your 401 error document.
Note that return false is required so that the page is not reloaded twice.

Facebook form post data not present on backend

I am attempting to post form data to my app using Facebook. My form is integrated with a dialog and I am using form.submit() to submit the form. Please see my code. The post data does not appear on the backend (e.g. load-cargo-radio, city-id, train-id), but the fb_sig* data does. Does anyone know if there are any caveats regarding posting form data with Facebook? Thanks!
Note: I have tried both using my server domain and my fb callback url for the form action. Neither works.
<div id="action_prompt">
Loading cargo...
</div>
<fb:js_string var="fbjs_load_cargo_select">
<div id="load_cargo_select">
<form id="load_cargo_select_form" action="http://railsacrosseurope.com/turn/load_cargo_select" method="POST">
<p>Your train has stopped in the city of Arhus.</p>
<p>Arhus produces the following goods:</p>
<ul>
<li>Dairy</li>
</ul>
<p>Your train is hauling the following goods:</p>
<ul>
<li>Timber</li>
</ul>
<p>What would you like to do?</p>
<input type="radio" id="load_cargo_radio" value="1">Load new goods</input>
<input type="radio" id="load_cargo_radio" value="2">Discard existing goods</input>
<input type="hidden" id="city_id" value="3" />
<input type="hidden" id="train_id" value="15" />
<input type="submit" id="submit" value="Submit" />
</form>
</div>
</fb:js_string>
.
.
.
<script type="text/javascript">
var dialog = new Dialog().showChoice('Load Cargo', fbjs_load_cargo_select, 'Okay', 'Pass');
dialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
frm = document.getElementById('load_cargo_select_form');
if (frm) { frm.submit(); }
dialog.hide();
};
dialog.oncancel = function() {
form = document.getElementById('redirect_form');
form.setAction('http://apps.facebook.com/rails_across_europe/turn/move_trains_auto/');
form.submit();
}
</script>
[/code]
The problem was not with Facebook. The problem was that I left out the "name" attribute for my input elements.