1

just having a problem here. i'm doing the UI of a web-based app using jquery, css. there's a shopping a cart, and i want to store the selected items in the session, i used jquery.session plugin. e.g. var $.session("var1","item1");

What i want is to dynamically store items into dynamically named variables. how could i do that?

thanks.

Svante Svenson
  • 12,315
  • 4
  • 41
  • 45
mars-o
  • 1,695
  • 4
  • 23
  • 38

4 Answers4

3

If there's a shopping cart, that data should be handled by a server side scripting language like PHP. I'm assuming at the end they will be charged via credit card? This kind of data needs to be secure.

In addition, that's a pretty big part of functionality to be handled by a non-secure client-side language like JS that can be turned off.

Just something to think about in the future..

2

One way that you could do that is to create a function that stores the 'session' variables. The session would have two parameters, the variable name and its value. For example:

function setSession(name, value) {

     $.session(name, value);

}

Whenever you need to set the jQuery session variable, just call the function as in:

setSession('var1', item1);
jonstjohn
  • 59,650
  • 8
  • 43
  • 55
1

Just use strings to build it up to what you want, like so:

function storeValueInCart(cartId, value) {
  $.session("var"+cartId, value);
}

You can also store arbitrary data on elements and use them, like so:

    $(".vote_action").each(function() {
        vote_id = $(this).attr("id").substring("action_".length);
        $(this).data("vote_id", vote_id);
    });
The above loops through each element with the vote_action class set. On each element it finds it gets the id attribute, which is a string like action_NN, and then chops off the action part. Then it stores this vote_id as arbitrary data on the element under the "vote_id" name.

0

Since the session function takes strings as parameters, just create these strings dynamically.

Svante Svenson
  • 12,315
  • 4
  • 41
  • 45
  • ah..ok. so, i just need to do "var"+ctr++ outside $.session()? ok. i see. but how do i retrieve? how do i know the number of session variables i used?... thnx – mars-o Feb 17 '09 at 11:31
  • According to the jQuery-session-site, there seems there is no way to find out how many, or what key/value-pairs are stored. If you name the keys (first parameter) using incrementing numbers, you could store the max-value in another key/value-pair. – Svante Svenson Feb 17 '09 at 11:38