Using Cookies or Databases?

Asked

Viewed 462 times

7

I need to create a cart where you store more than one data Example: ID_PRODUTO, ID_VENDEDOR

I would like to use Cookies pro system get lighter, but I found a big problem, the Cookie stores the data in 1 line:

COOKIE VALUE = ID_PRODUTO=1&ID_VENDEDOR=2&&ID_PRODUTO=111&ID_VENDEDOR=222&&ID_PRODUTO=999&ID_VENDEDOR=777

It is complicated to check if you already have the product in the cart. Any suggestions on how to decide the Cookie or Database?

  • 4

    The biggest problem is the cookie size limit. If you need to store a lot of data, it may not fit. So data volume is crucial for deciding whether to use a comic or not. If you decide to keep cookies, you will need more complex keys, or you won’t know which product is linked to which seller (I wouldn’t trust the order).

1 answer

10


The title of your question refers to the decision to choose to use cookies or a database to store information. The content of your question poses a problem about how information is stored in a Cookie and asks about an effective method of handling it. I will try to answer both questions.

Cookie vs Database

As already mentioned in comment from @bfavaretto, the information density is the largest decision point regarding the use of Cookies or use of a database to store information, even if temporary.

To help you decide, you can analyze this question where you try to understand the limits of Cookies and their feasibility:

Maximum number and size of cookies

In the end, only you can answer back whether Cookies are the best option when compared to a database regarding the work you are doing.

Personally, it would use a database or localStorage since we have the work prepared for substantial growth in the number of products in the trolley.

Information organized in a Cookie

In order to organize the information that will be stored in the Cookie in a way that makes sense, has some reading and can be worked with some effectiveness, I recommend using the function JSON.stringify (English) that allows you to serialize a value:

Serialize Javascript value into Javascript Object Notation (JSON) text

That translated:

Serialize a Javascript value in Javascript Object Notation (JSON) text

Practical example

Demonstration at Jsfiddle

// criamos um objecto
var meuDados = new Object();

// Criamos um sub-objecto para o nosso primeiro produto
meuDados.Produto1 = new Object();
meuDados.Produto1.ID_PRODUTO  = '1';
meuDados.Produto1.ID_VENDEDOR = '2';


// Criamos um sub-objecto para o nosso segundo produto
meuDados.Produto2 = new Object();
meuDados.Produto2.ID_PRODUTO  = '111';
meuDados.Produto2.ID_VENDEDOR = '222';

// etc...

This way we have information organized into a multi-dimensional object that we can convert into a JSON to store in the Cookie:

var jsonText = JSON.stringify(meuDados);

And the final result of the text to save to the Cookie is:

// linha de texto
{"Produto1":{"ID_PRODUTO":"1","ID_VENDEDOR":"2"},"Produto2":{"ID_PRODUTO":"111","ID_VENDEDOR":"222"}}

// visão estruturada da linha de texto
{
  "Produto1" : {
      "ID_PRODUTO"  : "1",
      "ID_VENDEDOR" : "2"
  },
  "Produto2": {
      "ID_PRODUTO"  : "111",
      "ID_VENDEDOR" : "222"
  }
}

With organized information we lose some space due to the characters that actually denote the data structure, but the work of processing the information is simplified.

We have already seen how to write the data, we will now see how we can collect and interpret where to use the function JSON.parse() (English) which allows us to transform the text with the correct denotation into an object:

The JSON.parse() method parses a string as JSON, Optionally transforming the value produced by Parsing.

That translated:

The JSON.parse() method optionally analyzes a string as JSON, transforming the value produced by the analysis.

// Ler o JSON de texto para um objecto como tínhamos antes
var meusDados = JSON.parse(jsonText);

// Função para procurar o produto
function procuraProduto(objecto, id) {
    for (var x in objecto) {
        for (var y in objecto[x]) {
            if (y=="ID_PRODUTO" && objecto[x][y]==id) {
                return true;
            }
        }
    }
    return false;
}

// Procuramos um produto em particular pelo ID
if (procuraProduto(meusDados, "111")) {
    alert("Yap, está cá!");
} else {
    alert("Ora bolas, não está!");
}
  • If you need a smaller format, you could use something like ...&ID_VENDEDOR=ID_PRODUTO, for example, 1=15&1=21&2=13. To parse, simply divide the string by & and then by =

Browser other questions tagged

You are not signed in. Login or sign up in order to post.