Use Cookies or Database?

7

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

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

  

COOKIE VALUE =   ID_PRODUCT = 1 & SALVER ID = 2 & ID_PRODUCT = 111 & ID_VENDER = 222 & ID_PRODUCT = 999 & ID_ENDER = 777

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

    
asked by anonymous 15.03.2014 / 23:52

1 answer

9

The title of your question refers to whether you decide to use Cookies or a database to store information. The content of your question presents a problem about how information is stored in a Cookie and questions an effective method of handling it. I will try to answer both questions.

Cookie vs Database

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

To help you decide, you can examine 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 if Cookies are the best option when compared to a database for the work you are developing.

I would personally use a database or localStorage as we get the job prepared for substantial growth in the number of products in the cart.

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:

  

Serializes the JavaScript value into JavaScript Object Notation (JSON) text

What translated:

  

Serializes a JavaScript value in a JavaScript Object Notation (JSON) text

Practical example

JSFiddle Demo

// 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...

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

var jsonText = JSON.stringify(meuDados);

And the final result of the text to save in 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 the information organized we lose some space due to the characters that actually denote the structure of the data, but the work of processing the information is simplified.

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

  

The JSON.parse () method parses the string as JSON, optionally transforming the value produced by parsing.

What translated:

  

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

// 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á!");
}
    
16.03.2014 / 02:49