Mr chinpansee
Mr chinpansee

Reputation: 375

Add values to the cookie using URL

I'm working on my webshop and since I dont want users to have to register to use the webshop, im using javascript cookies to hold the values the user has entered. But I want people who go to the webshop with a different url (for example: http://test.com/index.php?124&342), having 2 values in the cart, I made some functions to work on this. Here is the following code:

function getUrlVars() {
    var variabelen = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    var urls = $.cookie($.cookie('cart')) || [];

    for (var i = 0; i < variabelen.length; i++) {
        urls.push(variabelen[i]);

    }
}

if ($.cookie('cart')) {
    var Orders = $.parseJSON($.cookie('cart'));
} else {
    var Orders = new Array;
}


getUrlVars();

Where "orders" is the json array with the selected product-ID's. Now this is not working as I wanted to. It's not pushing the URL variables into the cart.

Okay UPDATE:

I succeed in pushing the URL variables in the cookie, but now the following problem accurs.

function UpdateTotals() {
            ToAddHTML = '<h1>Cart</h1></br>';
            console.log(Orders);
            TotalPrice = 0;
            for (var i = 0; i < Orders.length ; i++) {
                var Result = SubMenuItems.filter(function(v) {
                    return v.submenu_id === Orders[i];
                })[0];
                TotalPrice += parseFloat(Result.price);
                ToAddHTML += '<div class=orderd> <span class="order" Orders='+i+'> </span>'+'&euro;'+zoekresultaat.price+' '+zoekresultaat.title+'</br></div><hr>';
            }

The live website is on(nb. im using dutch description so the functions have different names):

Website

Upvotes: 4

Views: 285

Answers (1)

Jim Morrison
Jim Morrison

Reputation: 2177

If I understand the problem correctly this should do the trick:

// Given: page.html?109&10
// -----------------------
// Split the query string on '&', after the '?' and push
// each value into the array 'Bestellingen'
// -----------------------
$.each(document.location.search.substr(1).split('&'),function(key,value){ 
    Bestellingen.push(value);
});

You can replace your method haalUrlVars with the two lines above and you should find that items 109 & 10 are added to your list as though the were in the cookie when the page loaded.

Does that help?

Upvotes: 2

Related Questions