I am new to forms and am trying to get an understanding of what is going on. I have looked at lots of questions and tutorials, but feel unclear on certain points.
So far I have created the following form in an aspx page:
<form id="uploadbanner" enctype="multipart/form-data" method="post" action="#">
<span class="txtSmallGrey fl" style="display:block; width:200px; margin:15px; margin-bottom:2px">
<%= oUtils.GetContentText("Collect_Config_upload_sound") %>
</span>
<input type="file" name="SoundFile" id="SoundFile" style="margin:15px; margin-bottom:2px">
<input type="submit" value="Upload" id="submit" style="float:left; margin-left:245px; margin-top:1px; height:20px;">
</form>
and I have the following script at the top of the page:
<%
if(Request.Form["SoundFile"] != "")
{
HttpPostedFile file = Request.Files["SoundFile"];
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
}
%>
I have a reasonable understanding of AJAX so some of this seems familiar to me.
Now to explain what I understand:
The form is declared and given the id of 'uploadbanner'. As I am transferring a file I have to include 'enctype...' I am posting as it is more secure and more flexible.
The action term tells the form where to post to. In this case I have put the C# code at the top of the page so do not need to include an asp.net page address to process this. If I did, I would include an asp.net page, in the same way as I would for AJAX (I think?).
Anything with an input tag inside the form tags will be posted in the form, and will send the name and value.
When the submit button is pressed, the form will be submitted to the the server side code for processing. So far I feel I understand what is going on.
Now the parts I feel less clear about,
Is it the case the when the 'submit' button is pressed, the C# code
at the top of the page will be activated, and so if the field was
blank it would not do anything?
And if the button was pressed multiple times, would the form be
submitted multiple times?
If so, then this is much the same way as AJAX?, and the file will
simply be passed to the C# code, from where I can do what I need with
it?
My final questions is, can I submit the form using an alternate
method to the submit button, eg can I make a normal JavaScript button
and tell it to submit the form?
Is it the case the when the 'submit' button is pressed, the C# code at the top of the page will be activated, and so if the field was blank it would not do anything?
Yes, Every time your page loads it will run the C# code, One would assume that if you submit the form it will check the posted form data. It's probably best to check HTTP headers.
And if the button was pressed multiple times, would the form be submitted multiple times?
Yes, the form will be submitted multiple times.
If so, then this is much the same way as AJAX?, and the file will simply be passed to the C# code, from where I can do what I need with it?
It's similar in the sense of HTTP requests but your posting to the page with a file attached and then C# checks with the page has file attached by running the Request.Form and then Request.Files and Posts to the server.
My final questions is, can I submit the form using an alternate method to the submit button, eg can I make a normal JavaScript button and tell it to submit the form?
What do you mean by a normal JavaScript button? You don't have to use a submit button. As long as your passing in a file and the page is loaded, the code will still run. I have approach where as i post to a HTTPHandler. Code snippet below:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpPostedFile postedFile = context.Request.Files["Filedata"];
string filename = postedFile.FileName;
var Extension = filename.Substring(filename.LastIndexOf('.')
+ 1).ToLower();
string savepath =HttpContext.Current.Server.MapPath("/images/profile/");
postedFile.SaveAs(savepath + #"\" + user.uid + filename);
}
So when submitting i point to the HttpHandler.ashx which is a class that implements the IHttpHandler interface, Which in turn gets the current context.
Related
<form action="/devilmaycry/register?action=addtocart" method="post">
<input type="hidden" name="user" value="<%=user%>"/>
<input type="hidden" name="pid" value="<%=pid%>"/>
<input type="submit" value="Add to cart" onclick="add();"/>
</form>
i am using the above code to submit a form and add a product to cart
the java code it calls is as follows:
else if(n.equals("addtocart"))
{
String user = req.getParameter("user");
int pid = Integer.parseInt(req.getParameter("pid"));
k=o.addintocart(user,pid);
if(k==1)
{
pw.println("<h3>Added to cart !!!<h3>");
}
else
{
pw.println("<h3>Errror , try again <h3><br>");
}
it does add the product to the table but it changes the jsp page ... i tried to use requestDispatcher but the URL has many parameters so i want something else through which i can retain the same page and update the table also
In order to stay on the same page you need to use AJAX rather than submit the form in the traditional way. HTTP works in a request-response fashion, so when the user submits the form, the browser expects to receive a new page in the response from the server, and will thus refresh the page and render the new HTML it receives.
You have two options here:
Stick with the traditional HTTP form submission request-response approach, and when you receive the request on the server to add an item to the card, after you add the item to the card, rebuild the URL of the page that is showing the information to the user. In this case it is important to use the 'Redirect-After-Post' approach (i.e. in the response to the form POST you put a redirect to the page). Otherwise if the user refreshes the page by pressing F5, the form data will be resubmitted again and the item added again to the cart.
Go for an AJAX approach. In the add() function, you need to submit the form using Javascript. If you are using JQuery it makes it very easy for you to do this. There are various questions / examples if you search around, such as the one here.
In the latter case you will need to change a bit how you process the information from your Servlet but its the only way to get the browser to stay on the same page (without reloading it). You also have the success and error handlers, which you can use to show a message on the screen to display the result.
I am writing code for a small webproject using js and jquery. In it, at some point, onclicking a button, i create a dialog. the dialog has a form within it with a name field and some number fields. I am supposed to check user inputs and send them to server, along with appending the name field to a list in the browser, to intimate user, one more item has been added. Two strange things are happening -
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
2) The name entry doesn't get appended to the list. Its as if the whole page refreshes after the submit. With the original default entries of the list of names.
Anyone has any ideas on why this is happening? Would post some code for your aid.Please don't suggest to use Ajax instead. I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
<div id='dialog' title='Define New Matrix'>
<form name='form1' id='form1' method='post'>
<fieldset>
<label for="Name">Name</label>
<input type='text' name='nameofmatrix' id='Name' class='whitepanes'><br>
<label for="a11">a11</label>
<input type="text" name='a11' id='a11' class='whitepanes number-field'><br>
<label for="a22">a22</label>
<input type="text" name='a22' id='a22' class='whitepanes number-field'><br>
<button id='submit_button'>Submit</button>
<button id='cancel_button'>cancel</button>
</fieldset>
</form>
<p id='tip' style='color:red;'><i>All fields are required</i></p>
</div>
<script>
//#button_define is a button on whose clicking the dialog opens.
$('#button_define').click(function(){
$('#dialog').dialog('open');
$('#tip').html("<p style='color:red; font-size:small'>All fields are mandatory</p>");
});
$('#submit_button,#cancel_button').button();
$('#cancel_button').on('click',function(){
$('#dialog').dialog('close');
});
$('#submit_button').click(function(event){
event.preventDefault();
var name=$('input[name=nameofmatrix]').val();
//Validate is a function which returns a bool if validation proceeds correctly
var isCorrect = Validate();
if(isCorrect){
//if validated correctly then add to list
$('#form1').submit();
//$('#dialog').dialog('close');
$('#selectable').append("<li class='ui-widget-content'>",name,"</li>");
}
});
</script>
Its as if the whole page refreshes after the post. with the original entries.
That's precisely what happens. Though I'm not sure where you're submitting the POST request to since there's no action attribute on your form. But a standard non-AJAX request triggered by a form sends the request to the server and then renders the response from the server. If the response is this same page again, then this same page will be rendered again.
JavaScript isn't going to remember the state of the previous page when it loads this new response. Even if they're the same page, they're two separate responses from the server. So...
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
The dialog isn't closing. After the page refreshes you're in an entirely new page context. It didn't close, it just hasn't been opened yet in this context.
2) The name entry doesn't get appended to the list.
There's nothing that would cause this to happen when the page loads, so in the new page context it doesn't happen. Your server-side code would need to include this content in the response to the POST request.
I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
Included in that misunderstanding is the fact that AJAX is part of JavaScript. (The "J" in "AJAX" stands for "JavaScript.") It's not "switching to some other technology." It's taking advantage of the capabilities of the technology you're already using. All AJAX does, really, is send requests and receive responses to/from the server without refreshing the page context.
You are not properly appending the name. The concatenation operator is not a comma, but a + in javascript:
$('#selectable').append("<li class='ui-widget-content'>" + name + "</li>");
Next, the form refreshes because you are submitting the form using $('#form1').submit();. If you do not want the page to refresh while submitting, use ajax.
There is a PHP-generated HTML 4 transitional page that is used to edit data from a database of a single record. The user has two options: to store changes or delete the record. I use a form with controls (some of them are hidden):
<form method="post" action="object_mod.php"><!-- this is another file -->
<!-- inputs follow -->
As I want to process two actions ie. delete or save a record I put two submit buttons on the form, before </FORM> tag:
<input type="submit" id="btnSubmit" value="Save">
<input type="submit" id="btnDelete" value="Delete">
</form>
Because the user should confirm deletion I added the following onclick event:
<input type="submit" id="btnDelete" value="Delete" onclick="javascript:deleteRecordConfirm();">
(I also tried without javascript: and onclick="javascript:deleteRecordConfirm(); return true;"), but it doesn't submit a form.
The JS function is
function deleteRecordConfirm(){
if(confirm('Are you sure to delete?')){
document.getElementById("field_action").value=-1;
//document.forms[0].submit();
return true;
}
}
This field_action is set to -1 so I know in object_mod.php that I want to delete record rather than save it.
Here go question, why this form doesn't submit on deletion?
I think it would be good if a user has Javascript disabled to submit a form anyway, even without confirmation so that is why I use <INPUT TYPE="submit"> for deletion. Is it a good idea? I was thinking about giving two independent forms (in fact deletion should have only one hidden field with record id) with their own submit buttons, one for deletion and the other for saving.
In fact the page will work in some kind of intranet, with users who I trust and I'm not afraid of hacking or something, but any security remarks are also welcome.
(I tested it on Firefox 19.0 and Javascript console shows no errors, w3c validator says it's a valid page).
The form should submit according to your code. The only thing I spot is that you should terminate the input tags with />.
BUT... this way, even if the the confirm is cancelled, the form will be submitted. Use the form.onsubmit handler and if that returns false, the form will not submit.
I dont think #B3aT's answer is right in that not unconditionally the best way to "externalise" so to say. Many the the simplest is the best.
I think the best way is to "externalize" the actual form posting.
//make regular buttons (not submit)
//call your own functions (save and delete)
//after you have done your logic do document.forms["myform"].submit();
Another solution is to add a checkbox named "delete" and rename the "save" button to "Done or do". And on server side, if "delete" is activated, then ..delete it.
Usually the "delete" is required "per entry" level (same user have multiple records), so you will have to make a separate button/link and eventually do an ajax request/access an URL with ?delete=1&id=3.
You need to make custom yes/no windows or use a jQuery plugin for it, the only browser standard is "confirm".
OK, it worked, and this was in fact very stupid mistake. The problem was with this button as it was outside the form. I was so sure that I have it inside that I did not review PHP code but copied all from script not the HTML output as I should have done.
As I understand this correctly the line document.forms[0].submit(); worked but it was not because it was button who submitted the form but document.form[0] object itself.
Thank you for all your answers. I will try this form.onsubmit hint from Marcell.
I am attempting to create an HTML form, that of which uses the submit button, to email me the data that has been entered (have that part covered) but also send the data to another external page (that can handle this request).
I can have it working by doing:
<form name="contactform" method="post" action="http://somesite.com/page.php">
But, I also need it to submit to a local page (form.php) at the same time.
I have tried javascript, by doing this for the submit button:
<input type="submit" value="Submit" onclick="return doSubmit();">
With this code in the source:
function doSubmit()
{
document.contactform.action = "form.php";
document.contactform.submit();
document.contactform.action = "http://somewebsite.com/page.php";
document.contactform.submit();
return true;
}
But when I do this, the information is not sent to my email, and instead of displaying the result on form.php the page is refreshed.
Any ideas on how I can make this work in a simple way?
You can't submit to multiple actions at the same time as the browser can only load one request per window at a time by design. Some solutions include:
Just do the email handling with the same server script that does the form input handling
Send the form data to the email script via ajax and then submit the form normally on completion, e.g.
I would recommend adding/altering a function in your php script. Then you can do whatever you like with the posted data.
Obviously you cannot submit two forms. You can try either of these two things:
Make one of them an ajax request, and set it to be executed before submit.
Execute the second php file directly from the first one in the server
side.
My idea : when click a filename will get the path of file ,
then create a form and submit this form,
but i don't know how to submit ,
when submit , undefined form cause elements was created at same time
help me, thank !
<p onclcick='startUpload(this.value)'>PATHTOFILE<p>
function startUpload(file)
{
var form = '<form name="form_upload" method="post" enctype="multipart/form-data" action="upload.php">';
form += '<input type="file" name="upload_logo"/>';
form += '</form>';
// code to submit . i don't know how :(
}
first off, p tags have no value. this.value needs to change to this.get("text").clear(); second, you cannot pass on the value to the file dialogue object from an external source - else, what's to stop you from changing that value to say, c:\autoexec.bat or /etc/passwd or similar, you get the idea - a major security flaw in the design.
so the form creation is fine but it needs to be user driven - they select the file, they submit (or you submit on select for the file input).
to plain submit using your current html you'd do:
new Element("div", {
htm: form
}).inject(targetDiv);
targetdiv.getElement("form[name=form_upload]").submit();
if you need to ajax it, then say so - there are some methods available through html5 or an iframe shin or a flash uploader that can allow you to do so without a page reload, neither of which qualifies for progressive enhancement though.
good luck