Search code examples
javascriptjquerydomdata-storage

Safe way to store data for button clicks


I am trying to find out what the safest way to store data for use when the user clicks on a button.

I know that you can store data in attributes(either the value attribute or a data- attribute) of the button tag like so:

<button type="button" value="1" data-value="1">Click me!</button>

But the problem with this is that the user(probably really only advanced users) can manipulate the value with firebug or some other app and THEN click the button and send over different data. I fully understand that I need to check the input before I try to do anything with the sent data.

I also found out that I could use jQuery's .data() to attach data to dom elements, which seems a bit more useful. I'm not exactly sure how the data is stored, but I assume its harder to manipulate.

What got me really interested in this question was when I was looking through Soundcloud's code in firebug, I saw that none of the "like" buttons had data attached to the buttons. I tried deleting/manipulating elements/data and the buttons still worked. So it got me thinking that they are probably using a similar process to what jquerys data() is doing.

I just want to know if there is a safer way to store data or a way so that the user can't manipulate the data before clicking the button.


Solution

  • Consider this function:

    function setupPrivateData(element) {
      var private = 1; 
      element.setPrivate = function ( d ) { private = d; }
      element.getPrivate = function ( ) { return private; }
    }
    

    When called with some DOM element it will add two methods to it: .setPrivate(val) and .getPrivate().

    These are the only methods that will allow you to access and modify that private variable associated with the element.