russianroadman
russianroadman

Reputation: 191

HTML cookies cannot be created fully JS

function writeCartToCookie(){
    var stringRepresentation = "";
    for (i = 0; i < cart.length; i++){
        stringRepresentation += "serial" + i + "=" + cart[i][0] + "; ";
        stringRepresentation += "price" + i + "=" + cart[i][1] + "; ";
        stringRepresentation += "name" + i + "=" + cart[i][2] + "; ";
        stringRepresentation += "qtty" + i + "=" + cart[i][3] + "; ";
    }
    stringRepresentation += stringRepresentation + "max-age=" + 60*60*24*7;
    /* ALERT BEFORE WRITE */ alert(stringRepresentation);
    /* WRITE */ document.cookie = stringRepresentation;
    /* ALERT AFTER WRITE */ alert(document.cookie);
}

result:

first alert message:

serial0=12312312; price0=₽810,000; name0=КОЛЕНВАЛ-F; qtty0=4; serial1=2345465; price1=₽820; name1=ШТУЦЕР ТИТАН; qtty1=85; serial2=956; price2=₽590,000; name2=ФОРСУНКА МЕГА; qtty2=1; serial3=2356996; price3=₽100,000; name3=РАСПРЕДЕЛИТЕЛЬНЫЙ ВАЛ; qtty3=4; serial0=12312312; price0=₽810,000; name0=КОЛЕНВАЛ-F; qtty0=4; serial1=2345465; price1=₽820; name1=ШТУЦЕР ТИТАН; qtty1=85; serial2=956; price2=₽590,000; name2=ФОРСУНКА МЕГА; qtty2=1; serial3=2356996; price3=₽100,000; name3=РАСПРЕДЕЛИТЕЛЬНЫЙ ВАЛ; qtty3=4; max-age=604800

second alert message:

serial0=12312312

So "serial0" is the only value that has been written Why?

Upvotes: 0

Views: 35

Answers (1)

Pointy
Pointy

Reputation: 413712

Only one cookie can be set in any single

document.cookie = "something=something";

assignment. It's an old and strange API. Thus you'll have to set each cookie inside your loop. (Also, make sure i is declared with let or var somewhere.)

Each cookie will need it's own set of flags, like max-age.

Upvotes: 1

Related Questions