Tuesday, June 16, 2009

javascript code for preventing data loss in web form.


HTML forms are used in webpages for collecting data from users. The Form will be submitted on clicking "submit" button in the Form.

The form data will be inserted into database table only when the form got submitted, otherwise the entered data will not reach the database.

Assume that an User fills a user registration form in a website and forgot to click Submit button and then navigates to some other page in the website.

In this case all the details entered by the user will be lost. He needs to enter it again to submit the form for storing the details in the database.

So, to avoid this issue we need to write a code which will give warning to the user when he leaves from the form without submitting it.

We need to follow below steps to do it.
-on loading a page we need to initialize a Boolean flag to indicate that no data available for saving it.
-Change the Boolean flag when typing any data in the form to indicate that we need to save the data before leaving from the page.

-call a function when clicking any link in the page to give warning/alert message based on the Boolean flag value.


Find below the sample javascript code.



var ischanged;//This variable used as flag to check whether user clicked submit button or not
function initialize_ischanged()//this function triggered when body load event
{
ischanged=false;
//alert(ischanged);

}
function check_buttonpressed_ischanged()//this function invoked when submit button get clicked.
{
ischanged=true;
//alert("ischanged is true");
}
//following function called when clicked any links in page, to check whether user clicked submit button or not
function check_ischanged()
{
if(ischanged==false)
{
if(confirm("Do you want to save this game? [ Click Save button ]"))
return false;
else
return true;
}
}


Find below the Reddit users comments for this post.



msloyko
call a function when clicking any link in the page to give warning/alert message based on the Boolean flag value.

Or, we can just set up an unload event handler.

JasonMaloney101

* Wouldn't unload still be called when the page is unloaded while submitting the form?
* On an AJAX-based site, it is possible to click a link on the page that will replace the form (and the rest of the page) with other content, all without unload() ever being hit.

suddo
That's why you add an onSubmit event on the form to disregard the unload event.



More Articles...

No comments:

Search This Blog