Documentation You are here: start » v » 2.0 » session_variables

The Myriad Uses of Session Variables

What Session Variables Are

“Session Variables” allow you to store information (as name/value pairs) in a user's cart, independently of any products in the cart. Unlike a product, which is visible in the cart and added by the customer, session variables aren't necessarily visible to the visitor, nor would the visitor know that a session variable has been set. You can think of session variables as a way to attach extra information to the session (fancy that) for you to use later.

Potential Uses of Session Variables

Though you could use session variables for any number of integration or data tracking purposes, the most common uses are:

  • Analytics. For example, the Google Analytics integration relies on session variables to maintain (Google, not FoxyCart) session states between your site, the cart, the checkout, and the receipt.
  • Affiliate tracking systems. While most affiliate systems track primarily with cookies, there are situations where using a session variables may be more desirable.
  • Storing user information. Sometimes it may be necessary to attach data to a customer that impacts later functionality. Perhaps adding a flag if they've already visited an upsell page (to prevent showing them the same page). Or adding an ID for a separate system for use with later synching.
  • And much more.

How to Set Session Variables

Setting a session variable is as easy as adding an h: prefix to any value being passed to the cart. Here's a quick example of adding a product with a color value equal to blue, and a session variable named referrer set to charlie.

<!-- First, a link -->
<a href="https://YOURDOMAIN.foxycart.com/cart?name=A great product&price=5&color=blue&h:referrer=charlie">
	Buy this Great Product!
</a>
 
<!-- Next, a form -->
<form action="https://YOURDOMAIN.foxycart.com/cart" method="post">
	<input type="hidden" name="name" value="A great product" />
	<input type="hidden" name="price" value="5.00" />
	<input type="hidden" name="color" value="blue" />
	<input type="hidden" name="h:referrer" value="charlie" />
	<input type="submit" value="Buy It Now!" />
</form>

Either of those would add the product to the cart, but would also add the referrer value to the session, so your JSON would include something like this:

{
...
	"custom_fields":{
		"referrer":"charlie"
	},
...
}

Notice that the custom_fields is at the top level of the JSON, not associated with specific products being added to the cart.

How to Access Session Variables

Given the intended usage of session variables, it shouldn't be surprising that these values are not displayed to the user at any point, but they are accessible via the JSON cart object during the user's visit, and via the transaction XML datafeed or the API after the transaction is completed.

Site Tools