1

I am trying to find the best methodology and have the cleanest code as possible on a project that I am working on.

I am using php and jQuery and displaying information on the page via ajax. When something changes on the page, some of the variables that are passed back into the page change. I need to store these values for other scripts on the page to use. What is the best approach for this.

Currently I am just storing these variables in hidden input fields with id's and then using jQuery to access them when needed. Is this a good approach or is there a better methodology? I don't want to have junky code that other developers look at and use and their punch line to their jokes.

Thanks!

LargeTuna
  • 2,694
  • 7
  • 46
  • 92
  • 3
    Use an object in window, like `window.yourApp = {}` then add something to it like `window.yourApp.someData = 42`. – parchment Jul 15 '14 at 17:20
  • consider defining the variable as Global by defining outside the function? – Imran Jul 15 '14 at 17:21
  • You can store these variables in your javascript as global variable look [here](http://stackoverflow.com/a/4862268/1852589).Besides that you can use localStorage to save the data on the client computer for usage see [here](http://stackoverflow.com/a/2010948/1852589). – S.Pols Jul 15 '14 at 17:21
  • writing them to hidden elements only makes sense if those fields are supposed to be posted somewhere. If not, parchment's suggestion is probably one of the most universally accepted solutions. window.var will work fine and no future developers are going to be confused by it. localStorage may be overkill unless you need the values to remain after a page reloads or something – Kai Qing Jul 15 '14 at 17:23
  • Thanks for the feedback, this gives me a great place to start – LargeTuna Jul 15 '14 at 17:25

2 Answers2

1

I find storing the variables inside your script is faster, especially since you're using them with existing JS. I would go further than some of the comments, however. If you're working with a series of fields and methods, it's best to build a JS object and keep everything together. This has the added benefit of being viewable inside your DOM inspector (Firebug, etc).

function MyClass(obj) {
     this.myvar = obj.val
}

MyClass.prototype.myFunc() {
    console.log(this.myvar);
}

newobj = new MyClass({"val":1});
newobj.myFunc();
Machavity
  • 30,841
  • 27
  • 92
  • 100
0

You can make use of HTML5 sessionStorage object

an example of how you set it

sessionStorage.setItem("myKey", "myValue");

please check documentation below

Here

Digital fortress
  • 737
  • 8
  • 18
  • 31