My HTML form is clearing automatically after I click the submit button. Any idea how to stop this from happening?
Here's the opening tag for the form:
<form onsubmit="return math()">
One popular approach is to utilize a server-side language such as PHP which reads all the get values and recreates the HTML of the page using a template and substituting in variables.
<input type = "text" name = "Textbox1" id = "Textbox1" value = "{$_GET[Textbox1]}"/>
I've written it out as $_GET directly, but you'd really want to make sure the value was scrubbed so you don't get arbitrary html injection.
A little bit more complicated you could approach this purely client side and utilize javascript to parse the address bar and extract the values submitted to your page (assuming it wasn't submitted with POST as the method). Then you can dynamically repopulate the fields client side.
when you click submit the page refreshes. You'll probably need to return a page with the value of the forms set to what was in when it was submitted.
If math() returns false your data won't disappear but it won't sent data to the server either. If you want to send data to the server you could make a XMLHttpRequest.
Related
I am looking for a library to restore html form fields (inputs, selects, checkboxes and everything else) state using javascript. State of the form should be previously saved in php's $_POST data or other serialized format.
I have html form and form validation in PHP.
PHP receives form fata on POST request and validates it, if user made a mistake - PHP displays this form again with restored values.
This problem appeares again when user wants to edit some previously saved data, and again we need to restore form state.
Usually I restore form state using PHP twig template like so:
<input type="text" name="anyname" value="{{anyname}}>
But I realised that there should be way to restore state using just one line of javascript code like so:
<script>
RestoreMyFormDataEasyWayIDontWantToWriteTwigTemplateAgain("formid",
{{$POST | json_encode(constant('JSON_UNESCAPED_UNICODE')) | raw }});
</script>
Without touching html and fields values.
This should be already solved, but after hours of googlin I can't find this javascript library. Please help!
I am trying something different to check if it is feasible. Otherwise best alternative way is to send data using querystring.
I have a html page which has list of students. when user clicks on perticular student for edit, this html page should take student ID and redirect to another html page, which will load respective student details for editing.
Here, I want to send data using "POST" method to hide studentID from URL (querystring), so I created a hindden form (method="POST" action="edit.html")on list html and put one hidden field under it. on lcik of edit button on list, I am setting value to hidden field & submitting form.
Now this redirects properly to edit html page and also when I see this flow in chrome developer tool, I can see this form value under headers sections - Form data. Now I am trying to fectch this form data on edit html page load e.g. in JQuery under document ready function or simple in javascript.
with alternative option if I create hindden form (method="GET" action="edit.html") then the hidden field value which I am setting is showing up in query string and also in chrome developer tool, it is showing under headers - query string parameters. This query string parameters can easily be accessed using location.search and then play around and will get expected value.
Here id I have taken just example, however in actual scenario, I need to send multiple values or may be objects which I dont want send thrugh query string. So I thought to submit form with POST method and retrive values on next HTML page load thrugh javascript on jquery.
HTML
<form style="display: none" action="jquerywebapidoestudenteditpoc.html" method="post" id="formEdit"> <input type="hidden" id="id" name="id" value="" /> </form>
JQuery
$(document).on("click", ".edit", function () { var id = $(this).data("id"); $("#id").val(id); event.preventDefault(); $("#formEdit").submit(); });
If anyone came accross this situation or implemented it in very appropriate way, would be very good.
In other words, I would like to implement is:
list.html will post data to server (.NET Web API)
At same time list.html will redirect to edit.html
On load of edit.html, response from server will be loaded on page.
Query string is part of the "identifier" of the subsequently loaded page (or any other resource). As such, it is accessible from the page. Data sent in the body of a POST request are different - they are meant for the server only and are inaccessible from the subsequently loaded page.
However, if you wish to make the data sent using POST available to the next page, you can always inject it into the page manually. Using PHP (as an example), it could look something like this:
<script type="text/javascript">
var postData = <?php json_encode($_POST); ?>;
</script>
If you just want to pass data from one page to another and leave the server out of it, you may either use GET (query string) for exposed communication or use cookies for "hidden" communication.
Bsically, what I understood after going through lot many blogs ans sites, I have to have a client controller (javascript based) which will take care of which view has to load and post data.
This I was able to achieve using AngularJS, where I can configuration can be done for routing and by same, I can post data & receive its whatever output on another view/ form (so called page).
e.g.
$routeProvider.when("/orders", {
controller: "ordersController",
templateUrl: "/app/views/orders.html"
});
AngularJS Rocks !!!
--edit--
(Trying to rephrase my question to be less confusing..)
My understanding is that you should validate forms both client and server side in case Javascript is not working.
How do advanced developers accomplish this in a seamless interface (if one had to describe in a general manner)?
Currently I have Javascript validating my input fields on the fly with 'onkeyup ()', highlighting invalid fields.
If I run the same validations with PHP after the user submits, then I have to redirect to the form if there were any errors, refreshing the page.
I thought this method was lacking sophistication.
What would be the best method?
Thanks in advance.
--- original question below ---
So I created a form with client side javascript to validate the input as the user types. It highlights the boxes w red borders if the data is invalid (using javascript to alter the css). I would like to re-validate the same data with php server side in case of any problems with javascript client side.
I am trying to figure out what is the proper (or best) way to accomplish this.
Currently the form action is setup to go to "register_post.php" after user hits submit.
--
So do I just validate the form data in PHP in "register_post.php", and redirect back to the form page if something is invalid, or is there a more sophisticated way to do this?
One annoying result of this is the page refreshing when the page is redirected.
Is there a more sophisticated way to do this?
--
Another related question is - should I prep my code for javascript not working at all? ..since currently, I use javascript to highlight the fields if the data is invalid. The user will have no indication of which fields are invalid without js.
please bear with me as I am a beginner.
You are trying to valid the post data with PHP and without refresh the page, I don't know if I get your point right. If you want to valid the data with PHP and without refreshing page, you could use AJAX. You can use javascript to post data to a PHP script and deal PHP return data.
An example of jquery ajax method :
<script>
var validDataArr = ''; //data need to be valided
$.ajax({
type:"post",url:"http://"+top.location.hostname+"/valid.php",
data:validDataArr,
success:function(context){alert(context);}
});
</script>
While submitting the form , call a javascript function to validate the fields and throw an error if it not suits.
you can call a js function as below
input type="submit" name="Submit" id="button2" value="Submit" onClick="javascript:verify()"/>
Try this , this will help you to understand the basic validation
http://jsfiddle.net/NWWL4/15/
I'm sending form data to an iframe (<form target="myIframe" ... >) because I need to upload a file and because I don't want to reload the page.
The problem is that I need to encrypt some data of the form. Surely I can replace values in form with encrypted values but it would not be really user-friendly. Is there some kind of callback to adjust the data of submitted form in javascript/jQuery?
Thanks!
Just use SSL.
<form action="https://..."
You need to load the page that displays the form via SSL to, otherwise it can be interfered with by a man-in-the-middle attack.
Can anybody tell me how to assign javascript variables to jsp request or to jsp session.
I am doing something like this
Here deletedRows is a hidden field.
var del=45;
document.getElementById("deletedRows").value=del
alert(document.getElementById("deletedRows").value);
<%String del_values = request.getParameter("deletedRows");%>
<%request.getSession().setAttribute("del_rows", del_values);%>
I don't get the value of del in my servlet.
JSP gets compiled on the server. All the client gets is the "output" of the JSP: the HTML, CSS and Javascript.
The Javascript gets executed after this. Meaning everything in the JSP has become HTML et all when the javascript executes. You way want to think this as the Java/JSP part has "completed" and now the HTML/Javascript part takes over.
Now you want to pass on some value calculated/manipulated via Javascript back to the server. (I think this is what you mean when you say "assingn javascript variables to jsp request or to jsp session"
For this you have to submit the page to the server, and these values should be part of the form that is being submitted.
You may already have these values in some HTML elements (like a <input> or <select>), if not you can create hidden elements and populate these with the values before submitting the <form>.
In the code you have provided, you are populating the hidden field correctly, but you have to retrieve the value in the servlet, not in the JSP itself. Also, make sure that the hidden field in in a <form> and that form is submitted.
Once the form is submitted (to a servlet) the values can be retrieved in the servlet via request.getParameter.
There are few other mechanisms to send a value to the server, using a URL parameter or via Asynchronous (AJAX) requests, but I am not sure whether you are looking at these also.
Any form fields, including hidden fields, that are submitted from the browser will be accessible in your JSP using request.getParameter("fieldname");. Query-string parameters may be accessed the same way.
Make sure that your form fields have a name attribute specified because it is that name (not the id attribute) that becomes the parameter name in your server-side code.
What you've already done in the little bit of code shown in your question, i.e., set the hidden form field to have the value of a JavaScript variable, should allow that value to be submitted and then accessed in the server-side code. But it's hard to see why it is not working without seeing at least some of your form HTML, particularly the definition of the hidden field. It would also help to see how that is being submitted. (I'm assuming it is being submitted: if you are trying to make all of that code run just on the server it won't work, because the JavaScript is treated as document content by the server, it isn't executed. Again, I can't really tell how you're using that code without seeing more of the surrounding JSP.)
UPDATE: I see that your code has been formatted since I started typing my answer. You aren't expecting all five lines to run on the server are you? The JavaScript code only runs on the client browser after the page is rendered. The Java code in between <% %> is executed on the server before the page gets to the browser and so can't access JavaScript at all. Anything not in the <% %> tags is simply sent to the browser as is - the servlet doesn't interact with it as such.