Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better approach than hidden field to store data in html

I'd like to know if a better approach exists to store data in html content.
At the moment I got some values stored in my html file using hidden field. These values are generated by code behind.

Html:

<input type="hidden" id="hid1" value="generatedValue1" />
<input type="hidden" id="hid2" value="generatedValue2" />

And therefore I get those values on client side using jquery, in order to pass them to an ajax request.

JQuery

$.ajax({
  data:{
     var1 : $('#hid1').val(),
     var2 : $('#hid2').val()
  }
);

So is this the correct way to do this, or does it exist a smoother solution to achieve the same result? Since I don't need these values to be posted on page submit the input hiddenis probably gross.

like image 507
nubinub Avatar asked Aug 02 '13 09:08

nubinub


People also ask

How do you hide the input field in HTML?

The <input type="hidden"> defines a hidden input field. A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted.

Is input type hidden safe?

Since they are not rendered visible, hidden inputs are sometimes erroneously perceived as safe. But similar to session cookies, hidden form inputs store the software's state information client-side, instead of server-side. This makes it vulnerable.

What attribute should be used for a hidden value?

The hidden attribute is a boolean attribute. When present, it specifies that an element is not yet, or is no longer, relevant.


1 Answers

What I usually do is adding the values as data- attributes to the html form:

<form data-field1="generatedValue1" data-field2="generatedValue2">
...
</form>

And then, retrieve them with jQuery:

... 
$form = $( my_selector_to_take_the_form );

data:{
     var1 : $('form').attr('data-field1'),
     var2 : $('form').attr('data-field1')
  }

With this, you won't post any hidden field

like image 74
Federico J. Avatar answered Sep 29 '22 01:09

Federico J.