Radio buttons in form do not transfer to another web page - javascript

I can not see why my code does not take me to the specified webpage when dealing with my radio buttons:
<form name="login" onsubmit="return validateForm()" method="post">
.
.
<input type="radio" name="ans1" id="yes">Yes<br>
<input type="radio" name="ans2" id="no">No<br>
<input type="submit" value="Login" onclick= "where_to_go();">
</form>
Script for where_to_go():
function where_to_go(){
if (document.login.getElementById('yes').checked) {
// Yes is chosen
document.location.href = "Admin_index.html";
} else if (document.login.getElementById('no').checked) {
// No is chosen
document.location.href ="Log-In_Greet.php";
}
}
Can someone please tell me where did I go wrong at?

You have two problems.
The first would be revealed if you had looked at your browser's Developer Tool's Console (and had log preservation enabled so it wouldn't be wiped when you navigated to a new page).
getElementById is a property of the document object and only the document object. It is not a property of document.logic so trying to call document.login.getElementById will throw an exception.
Second: You are running your JS when you submit the form.
The JS runs, tells the browser to navigate to one of two pages (or would if the above problem wasn't there), then the form submission continues and tells the browser to navigate to the form's action URL (which you haven't specified so is "the current URL"). This overrides the URL set in the JS.
The quick and dirty solution is to return false from the onclick function so that the normal behaviour of the submit button is cancelled.
The very slightly less dirty approach would be to use type="button" so you wouldn't be triggering a form submission in the first place.
The robust approach would be to write server side code which tests, on a POST request, which submit button was used and issues an HTTP redirect. This will work when the JS inevitably fails.
The cleanest, simplest, most reliable approach is to replace the radio buttons with simple links.

Related

Page changes when i submit the form

<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.

AJAX form checkbox array value gets "stuck" hanging

To make it really short and simple.
I have an AJAX form with method="GET", because I want to reflect all the changes in the URL (and for it to be accessible afterwards).
And the form is getting submitted to the server automatically when either of form elements is changed. On the server I rewrite the URL by using "history pushState".
I'm using Ruby-on-Rails as a server-side technology, if it matters.
One of the elements checkbox array (multiple elements can be chosen) - it is a list of parameters that user would like to see.
Now to the problem itself - suppose we visit this page for the first time.
None of checkboxes is checked so far. Then we check, for example, first checkbox.
Event is triggered - form is getting submitted -> url is rewritten properly.
Then I uncheck this checkbox -> event is triggered -> form gets submitted -> url is rewritten properly again!
Everything is correct so far.
And now the case that does NOT work.
I check this checkbox -> form is submitted -> url rewritten. Correct. And after that I hit "refresh" (F5 or Ctrl-R). I see that the checkbox is checked (as it is supposed to be), but ... I attempt to UNCHECK this checkbox, BUT for some odd reason on the server-side I still see this array value reaching the server. And, of course, it is reflected in the URL as well - it is present there (while it should not).
Sorry for messy explanation.
I'm I doing something extremely wrong?
P.S Form works correctly with ordinary parameters (fields, mainly).
P.P.S I was really curious - what is going on there, and I even attempted to see form values before they got submitted to the server by executing following code:
$("#my-form").on("ajax:beforeSend", function(){
console.log("FORM BEFORE SUBMISSION: " + $(this).serialize());
});
And the checkbox is absent there. Which is correct!
Thanks in advance!
P.P.P.S This is how my idea is implemented in general (very briefly):
<form method="GET" action="/search/?" id="my-form" data-remote="true">
... (some form elements here as well)
<input type="checkbox" name="search[types][]" value="1">
<input type="checkbox" name="search[types][]" value="2">
<input type="checkbox" name="search[types][]" value="3">
... (and submit button)
</form>
$("#my-form").change(function(){ $(this).submit(); });
Sorry everyone for wasting your precious time.
I found the problem - I used query-params as form "action" attribute, so submitting the form caused query params duplication every single time I refreshed the page before submitting it.
Easy :) Should have thought about it in the first place.

Jquery form submit behavior not understandable

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.

Onclick to submit a form

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.

How to "break out" of a JQuery color box

If I have a JQuery colorbox() using an iframe, and there is a <form> in that (e.g. login form), then:
If the submission of the form is not successful (e.g. mandatory field empty) then the form should be re-displayed with the error in the iframe
If the form is successful (e.g. password correct), the surrounding page should be reloaded with the result
Only the server request can know if the submission is successful or not (e.g. password correct for a login form), therefore one cannot use a target= parameter on the <form> tag. (As that must be set on the requesting page, where the success of the response is not yet known.)
How should one go about achieving that? Right now I do the following:
The <form> has no particular "target", i.e. the result is displayed in the iframe
If the form submission is unsuccessful, re-display the form in the iframe (the simple case)
If the form submission is successful then display a "response" page in the iframe, which contains Javascript, to refresh the whole page.
The Javascript looks like the following (the wicket:id="link" means that the web framework adds a href= to the link, to specify the resulting page which should be displayed in the whole browser window).
<a wicket:id="link" id="linkToSuccessPage" target="_top"></a>
<script>
$(function() {
top.$.colorbox.close();
top.location.href =
document.getElementById("linkToSuccessPage").getAttribute("href");
});
</script>
The trouble with this approach is, firstly it feels inelegant, but it creates an odd visual effect. The colorbox firstly closes, then there this redirect happens. The other option is not to close the colorbox, but then the contents of the colorbox gets replaced by a blank page while the redirect happens.
Any better ways? This must be a common problem, must have a common elegant solution?
P.S. I have to use the iframe method of the colorbox (rather than JQuery taking the form and placing it in a <div> in the page) for the following reasons: the web framework I'm using (Wicket) submits forms to a relative URL. The relative URL in the <form> is relative to the URL of the page containing the form (= the colorbox contents). If a <div> is used, then this form is inserted into the surrounding page which has a different URL, therefore the relative URLs in the form submission do not work.
I think you will still be able to do this without using an iframe, which will allow you to use inline content for your colorbox windows. Although this suggestion could be adapted for iframes, it's a lot cleaner when using inline content.
First, use this jQuery ajax form plugin to manage the flow of form submission. This will allow you to manage your success/error code without loading anything extra to, as you mentioned, refresh the page or reload the form. In your docReady, instantiate the ajax form like this:
$('#login').ajaxForm({
beforeSubmit: onSubmitForm,
error: onServerResponse,
success: onServerResponse,
url: "site.com"
});
Then you just do what you need to do in those 3 callbacks (all in the context of the parent page). Because you are defining the url here, whatever wicket does with the action attribute of the form won't matter. In fact, the html code for the form does not change except for the fact that now you can omit the action attribute.
With the use of inline colorboxes, switching between them while maintaining their data state (if any) is easy. First, assuming we'll give all of our colorbox links the classname "colorboxLink", we also need this in the docReady:
$(".colorboxLink").colorbox({
inline:true
});
And in a hidden div, set up all the colorboxes (one of which is your form):
<div style="display:none">
<form id="login" method="post">
Username: <input type="text" name="username" /> <br>
Password: <input type="password" name="password" />
<input type="submit" value="Go" />
</form>
<div id="error">
Error message.<br>
<a class="colorboxLink" href="#login">« Back</a>
</div>
</div>
So, the first colorbox window would open with a link, back/forward/other windows can be opened by links inside the colorboxes (as demonstrated in the "error" div), and to open colorboxes in a function:
$.colorbox({
open:true,
href: "#error",
inline:true
});
You will also be able to avoid that flicker when changing windows because the colorbox is never fully closed.
Check out a complete example at this jsfiddle.

Categories