Better approach than hidden field to store data in html

ajax, html, javascript, jquery

Solution

If you don't need those in a form, then just make them variables in your JavaScript. To output them, encode them via the `JavaScriptSerializer` class:

<%
    // Presumably somewhere in your C# code...
    JavaScriptSerializer serializer = new JavaScriptSerializer();
%>
<script>
var hid1 = <%= serializer.Serialize(valueForHid1) %>;
var hid2 = <%= serializer.Serialize(valueForHid2) %>;
</script>

(See note below about globals.)

Using them later:

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

Globals: As shown there, `hid1` and `hid2` end up as globals (on most browsers, they do when you use hidden fields as well). I recommend not using globals, but instead wrapping everything in scoping functions:

(function() {
    var hid1 = <%= serializer.Serialize(valueForHid1) %>;
    var hid2 = <%= serializer.Serialize(valueForHid2) %>;

    // ....    

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

If for some reason you have to use a global, use just one:

var myOneGlobal = {
    hid1: <%= serializer.Serialize(valueForHid1) %>,
    hid2: <%= serializer.Serialize(valueForHid2) %>
};

Using that later:

$.ajax({
  data:{
     var1 : myOneGlobal.hid1,
     var2 : myOneGlobal.hid2
   }
);

You can output an entire object graph to one variable (perhaps `myOneGlobal`) with the serializer:

<script>
var myOneGlobal = <%= serializer.Serialize(objectWithData) %>;
</script>

Problem

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 hidden`is probably gross.

Original source