Friday 28 February 2014

Submitting and Securing the form data with Javascript

Whenever you create a form in HTML, you use "action" attribute of the <form> to submit your form. Now if you are not using SSL, then the data that you are sending is not encrypted and not secure.
You can use javascript to encrypt the data and also submit the form. <form> contains a attribute or event "onsubmit" which is fired when user clicks on the submit button. We can use this event and submit form using javascript.

Here is a little demo of what you can do.

First create a simple form.
<form action="process.php" method="post" onsubmit="return submitForm(this.form)"> <input type="text" name="uname" id="uname"> <br> <input type="password" name="pass" id="pass"> <br> <input type="submit" value="Submit"> </form>
Now consider that want to send the username and password after encrypting it.
One way to do this is when user clicks the submit button, we change the values of the fields with the encrypted values.
The other way is to create form in javascript and values to it and then submit that form to server side.
Here is a little JS that does the same thing.
<script> //Dummy Encrypt function, returns the given data as it is. function Encrypt(data) { return data; } function submitForm(form) { //create a form element var f = document.createElement("form"); //set post and action attributes f.setAttribute('method',"post"); f.setAttribute('action',"process.php"); //Create a new element of type input var uname = document.createElement("input"); //Set its type uname.setAttribute('type',"text"); //give it a name uname.setAttribute('name',"uname"); //Encrypt can be any function that you define to //encrypt the given data uname.value = Encrypt(form.uname.value); //create one more to store password var pass = document.createElement("input"); pass.setAttribute('type',"password"); pass.setAttribute('name',"pass"); pass.value = Encrypt(form.pass.value); //add both to form f.appendChild(uname); f.appendChild(pass); //submit the form f.submit(); return false; } </script>
Here it we create a new form element, add child elements to it and submit is. The advantage here is you can choose your own encryption logic based on your needs and send the data securely to the server.
Ads :
Buy Kodak, Canon, Panasonic Cameras on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my

No comments:

Post a Comment