Creating a custom form for mechanize - javascript

I have a form on a website that is not directly selectable (as it is embedded in a javascript). So selecting it via mechanize browser object is not possible. What i want to do is to create a form just like that one and submit it using the browser object.
The form is
<form method="POST" action="Action.php?action=338&n=66&t=mine">
<input id="Mine66" type="hidden" value="22" name="duree">
<button class="boutonsGeneral" value="submit" type="submit" name="travail">
<span class="infoBoutonsGeneral" title="">
Work
<span id="dureeMine66" class="boutonsGeneral_duree boutonsGeneral_dureePlus">22 hours</span>
</button>
</form>
I used firebug and here is the info. The URL posted to is http://www.renaissancekingdoms.com/Action.php?action=338&n=66&t=mine
Parameters
duree 22
travail submit
Request Headers From Upload Stream
Content-Length: 23
Content-Type: application/x-www-form-urlencoded
What i have done so far is that i managed to log into the site and did the following
form = mechanize.HTMLForm('http://www.renaissancekingdoms.com/Action.php?action=338&n=66&t=mine', method='POST')
form.new_control('duree', 'hidden', {
'id' : 'Mine66',
'value' : '22'})
form.fixup()
br.form = form
br.submit()
But this doesn't seem to work. Any ideas where i am going wrong?

have you tried going directly to the link passing the post data as a parameter? like this :
r = opener.open('http://example.com/', data)
where data is the post data as a dictionnary

Related

How do I remove the query-string from my URL redirect

So i made this script below so that someone can enter an order ID and it would redirect to the following http://domain.tld/order/254441.
but it give me a query-string of ?webid=254441 at the end the URL. How do I remove this?
function urlRedirect(){
var action_src = "/orders/" + document.getElementsByName("webid")[0].value;
var form_url = document.getElementById('form_url');
form_url.action = action_src ;
}
<p>Search by ID</p>
<form id="form_url" onsubmit="urlRedirect()"><input name="webid" type="text" /> <input type="submit" value="Search" /></form>
And if anyone has suggestions on making the code better that would be great! :)
Thanks.
Change the method of your form to "POST".
<form id="form_url" onsubmit="urlRedirect()" method="POST">
HTTP POST requests supply additional data from the client (browser) to the server in the message body. In contrast, GET requests include all required data in the URL. When the method is GET, all form data is encoded into the URL, appended to the action URL as query string parameters. With POST, form data appears within the message body of the HTTP request.
See the documentation.

Create a secure POST link in express.js

I'm wondering if there's any simple way to create a link to submit a POST request to the server by using some Express.js technique or plugin.
It is also a way to secure more critical actions such as deletion of users. Adding also CSRF protection.
This is quite simple to do in some PHP frameworks such as CakePHP (with its postLink helper).
The way I'm doing it right now is by creating a hidden form by myself and adding in the html link an event to submit the form:
<form action="/users/delete/{{user.id}}" method="post" name="deleteUser{{ user.id }}" style="display:none;">
<input type="hidden" name="_csrf" value="{{ csrfToken }}" />
</form>
<a href="#" onclick="if (confirm('Are you sure you want to delete this user?')) { document.deleteUser{{ user.id }}.submit(); } event.returnValue = false; return false;">
Delete
</a>
This is exactly the way it works in CakePHP framework as well.
Inorder to create link to a POST request you can make use of client side techniques like capturing the click using javascript and generate a ajax post request to the server, Inoder to avoid CSRF attacks express middlewares are available(https://github.com/expressjs/csurf)
I ended up creating my own way to deal with them by using jQuery (but could also be done with javascript as well).
In my case, any link I want to send by POST will have to:
Contain the class postLink.
Contain the destination URL in the href attribute.
Contain the CSRF token in the data-csrf attribute.
Optionally contain the data-confirm attribute to specify a message to show as a confirmation before sending the POST request.
A link in the view would look like so:
<a href="/reject/23" class="postLink" data-confirm="Are you sure you want to reject this item?" data-csrf="NdiuZynW-thVmMqYPZqFFGxGcInQZn35mDf8">
Reject
</a>
Or without the confirm attribute:
<a href="/reject/23" class="postLink" data-csrf="NdiuZynW-thVmMqYPZqFFGxGcInQZn35mDf8">
Reject
</a>
The needed jQuery code is the following:
$(document).on('click', '.postLink', function(e){
e.preventDefault();
var url = $(this).attr('href');
var csrf = $(this).data('csrf');
var confirmed = false;
if(typeof $(this).data('confirm') !== 'undefined'){
if(confirm($(this).data('confirm'))){
confirmed = true;
};
}else{
confirmed = true;
}
if(confirmed){
$('body').append('\
<form action="'+ url +'" method="post" name="postLink" style="display:none;">\
<input type="hidden" name="_csrf" value="'+ csrf +'" />\
</form>\
');
$('form[name="postLink"').submit();
}
});
Basically what it does is applying the same technique of creating a form for each POST link that I mentioned in my question. The only difference is that I don't have to be bothered to create a form every time I want to create POST link.
This way the form will be created dynamically and appended to the body. Then submitted.
To make it secure I made use of the CSRF module for express.js.
If you don't need a secure POST link, then you probably could use the postLink plugin for jQuery.

jQuery ajax POST is sending an additional GET request

I am just starting with jQuery and I am trying to do a $.post request, but I am getting a post AND a get (see log below). I have searched a lot and only found cases where they were calling an ajax function twice.
My case is a dynamic table of forms where I want to send an ajax POST when a single form is submitted.
Here is my javascript:
$(document).on('submit', 'form.newguess', function (event) {
event.preventDefault();
alert($(this).serialize());
$.post("game", $(this).serialize());
});
Here is my JSP:
...<tbody>
<c:forEach var="player" items="${players}">
<tr>
<td class="namecell"><p>${player.key}</p></td>
<td class="guesscell">
<p>${player.value}</p>
</td>
<td class="inputcell">
<form class="newguess" action="game" method="post">
<input type="text" name="guess" />
<input type="hidden" name="player" value="${player.key}"/>
<input type="submit" value=">"/>
</form>
</td>
</tr>
</c:forEach>
</tbody>
And here is the log from my server:
23:32:41,617 INFO (http-localhost/127.0.0.1:8080-3) POST - Game
23:32:41,696 INFO (http-localhost/127.0.0.1:8080-3) GET - Game
I have tried to remove the $.post and then I don't receive anything, so it is definitely the $.post.
Any ideas are welcome, it must be a very dumb mistake.
Thank you.
I think you can use a normal button instead of
<input type="submit" value=">"/>
use
<input type="button" value=">" onclick="yourFunction"/>
Maybe thats why it is sending two times, one from jquery and another from the DOM (?)
Solved it! I knew it had to be something dumb.
This is my code on the server:
#RequestMapping(value = "/game", method = RequestMethod.POST)
public String postPlayerGuess(#RequestParam("player") String playerName,
#RequestParam("guess") String guess, Model model) {
System.out.println("POST");
gameService.setGuess(myself.getGameName(), playerName, newGuess);
return "redirect:/game";
}
Notice that redirect:/game at the end? yep, that it was. I was redirecting the response, so the client made another GET request.
Sorry guys, you couldn't have solved this one without the code on the server, my bad!
It is due to, you have put your form in loop. So that every first iteration your mentioned form method will post but after that all form will have get request by default.
You need to generate unique "name" for every form . To avoid multiple GET/POST request .

How to submit additional data along the file upload in dropzone.js?

I have this form in my html code:
<form action="upload" id="upload-dropzone" class="dropzone">
<input type="hidden" name="browser-path" id="browser-path" value="/">
<div class="browser-buttons rrtl">
<a id="browser-btn-upload">Upload</a>
</div>
<div class="lltr" id="browser-path-view"></div>
</form>
<script type="application/javascript">
Dropzone.options.uploadDropzone = {
clickable: "#browser-btn-upload",
};
loadBrowserContent();
</script>
As this document said, the hidden input field browser-path will automatically be submitted as POST data to server.
I have this code in my server side:
System.out.println(request.getParameter("browser-path"));
But this code always prints null to output!
How can I submit this hidden field to my server and how can I read it?
Edit:
Thanks to steeno, the form enctype is multipart/form-data so I have to read the fields from another way.
I assume you use Java as backend language?
As mentioned in the following question: HttpServletRequest get JSON POST data
the problem yould be the encoding of the post request. Maybe try to get the post data with getReader instead of getParameter.

to send a text file to server using javascript

I need to send a text file to server and get it saved. how can i do it using javascript???
There are all sorts of security issues surrounding this. Would you be happy to visit a website that would upload a file from your machine to the server?
For a generic website, where users are likely to have their permissions set to deny this sort of access it isn't possible.
If by chance, you are looking to do this for an application where you have control over the security settings for its users, and that you can guarantee its Windows and IE, then it is possible by reading the file and passing the details by posting to the server. See the following link : http://www.javascripter.net/faq/reading2.htm
However when you move away from IE or Windows, then you are going to struggle.
using ajax of course.
have a file on the server, PHP or ASP - depending on what your internet server is.
this file will accept the text file (data and name), and should also check for size and if this file already exists or not, and if all is ok- it will save it, and return a string "OK"
on the client, javascript side, just send the information to the server using ajax, or HTTPREQUST object - there's plentty of documentation for that around. and if you get back a response of "OK" then you know that it sent well.
even better: don't use HTTPREQUEST, but do dynmaic script tag insertion - where the source attribute of the script you're appending is that file on the server like:
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = "http://server/serverFile.PHP?filename=XXX&data=LONG STRING OF DATA REPRESTING THE DATA TO BE SAVED PROBABLY LESS THAN 2K IN SIZE AND ALSO YOU SHOULD ESCAPE OR ATLEAST URIENCODE IT";
document.body.appendChild(a);
and on the server file, serverFILE.PHP:
<?php
// some code to save the request variable [data].
// if all is ok:
alert("ok")
// or:
result = "ok"
?>
get it?
note: you'll probably have a limit of less than 2K on the file size.
Javascript is a front-end language. You may use php or any server side language.
You can create an Ajax equiv function make an iframe with width and height=0px then make it the target of the form with the file upload input and process it with the action PHP
<form action="upload.php" target="target" method="post"
name="uploadform" id="uploadform" enctype="multipart/form-data">
<label for="input_file_upload">Upload:</label>
<input onchange="document.uploadform.submit();" size="80"
type="file" name="file_upload[]" id="file_upload"
multiple="multiple" />
<input type="hidden" name="fileUpload" value="upload" />
<input type="button" value="Upload" />
</form>
<iframe id="target" name="target" style="width: 0px; height: 0px;">
</iframe>

Categories