How to attach custom session variable via javascript?

fileeefileee Member
in Help edited February 2016
We need to pass a referrer ID from the main page to the end of the checkout/receipt.

Now because the referrer variable is coming from the url as a query parameter(e.g. example.com?referrer=myniceshinnyreferrerID) i wanted to attach it globaly to the session. With links that is easily possible, but i don't wont to alter every link manually nor programatically(seems ugly to me to touch the DOM for that)

So i tried this


FC.client.on('render.done', function(params) {
//That is just for getting the url parameter see http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length == 1)
b[p[0]] = "";
else
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));

if(qs['referrer']){
FC.json.custom_fields.referrer = qs['referrer'];
}
});


On the main page with the side cart it works and the FC.json object was altered, however this is not passed and accessible anymore on the checkout page. So my question is, how can i set/edit custom session variables dynamically? I did not found any example of that in your documentation or the forum.
Comments
  • Okay maybe i found the solution.

    I need to call

    FC.client.request('https://'+FC.settings.storedomain+'/cart?h:referrer='+qs['referrer']);


    also with that i need to remove the whole render.done callback, as otherwise it will end in an infinite loop(as this request call triggers a rerender).

    Is that the right solution?
  • fc_adamfc_adam FoxyCart Team
    @fileee,

    Yes that's it - you would need to call the FC.client.request() function to alter the session. The JSON object available on the page is read-only.

    You'll still want to make this call within the FoxyCart events, to ensure that the FC object is initialised, but instead of render.done you'd use ready.done - which is called as soon as the object is ready.

    Finally - if you're calling this code on your own website, you'll need to wrap this all in an onLoad function. You can see details of that on https://wiki.foxycart.com/v/2.0/json#adding_a_coupon_or_session_value_automatically_using_jsonp
  • Yes thx, actually i'm using that inside my custom JS snippet that itself gets injected dynamically so that the FC object is already initialized then. see my other discussion here https://forum.foxycart.com/discussion/10666/optimize-custom-snippet-injection-developing-workflow
  • fc_adamfc_adam FoxyCart Team
    @fileee,

    Awesome. You'd want to use the ready.done if you're embedding the code directly into your own website rather than through the custom footer, but your approach looks great for there.
Sign In or Register to comment.