Storing data for a while

Asked

Viewed 505 times

2

Is there any way using the javascript cookies that I can store information for 3 hours for example ?

In my scenario I need to have a warning page, but I don’t need to store these records in a database. I need these warnings to stay for at least 3 hours on the page after they expire.

Searching about javascript found this cookie. So, basically I wanted you to have a textarea with a button of Submit, and when the user writes the warning and clicks on the button, the content of the textarea appeared in a div and stay there for 3 hours.

But I have no idea how to do that and I don’t know if it’s viable.

*Remembering here that would be several warnings. That is, it may be that the day may have more than one warning, so I wanted to show them all, and according to the time they disappear (expire) from the page.

Could someone help me ? Is there any other way I can do this without having to create tables and have that time to expire ?

EDIT

I made a code here that works. But I wanted to adapt it to my scenario. I mean, the warning stays there for 3 hours and then expires.

<div class="row">
<h3>Digite o aviso</h3>
<form id="frmCadastro">
    <textarea id="aviso" rows="10" cols="100"></textarea>
    <br />
    <input type="submit" value="Salvar" id="btnSalvar" class="btn btn-info btn-lg" />
</form>
</div>
<script>
    $(function () {

        var operacao = "A"; //"A"=Adição; "E"=Edição

        var indice_selecionado = -1;

        var tbClientes = localStorage.getItem("tbClientes");// Recupera os dados armazenados

        tbClientes = JSON.parse(tbClientes); // Converte string para objeto

        if (tbClientes == null) // Caso não haja conteúdo, iniciamos um vetor vazio
            tbClientes = [];

        function Adicionar() {
            var cliente = JSON.stringify({
                Aviso: $("#aviso").val(),
            });

            tbClientes.push(cliente);

            localStorage.setItem("tbClientes", JSON.stringify(tbClientes));
            return true;
        }

        function Editar() {
            tbClientes[indice_selecionado] = JSON.stringify({
                Aviso: $("#aviso").val(),
            });
            localStorage.setItem("tbClientes", JSON.stringify(tbClientes));
            operacao = "A";
            return true;
        }

        function Listar() {
            $("#tblListar").html("");
            $("#tblListar").html(
                "<thead>" +
                "<tr>" +
                "<th>Avisos</th>" +
                "</tr>" +
                "</thead>" +
                "<tbody>" +
                "</tbody>"
                );

            for (var i in tbClientes) {
                var cli = JSON.parse(tbClientes[i]);
                $("#tblListar tbody").append("<tr>" +
                                             "  <td>" + cli.Aviso + "</td>" +
                                             "  <td><img src='Imagens/edit.png' alt='" + i + "' class='btnEditar'/><img src='Imagens/deleta.png' alt='" + i + "' class='btnExcluir'/></td>" +
                                             "</tr>");
            }
        }

        function Excluir() {
            indice_selecionado = parseInt($(this).attr("alt"));
            tbClientes.splice(indice_selecionado, 1);
            localStorage.setItem("tbClientes", JSON.stringify(tbClientes));
            alert("Aviso excluído.");
        }

        function GetCliente(propriedade, valor) {
            var cli = null;
            for (var item in tbClientes) {
                var i = JSON.parse(tbClientes[item]);
                if (i[propriedade] == valor)
                    cli = i;
            }
            return cli;
        }

        Listar();

        $("#frmCadastro").bind("submit", function () {
            if (operacao == "A")
                return Adicionar();
            else
                return Editar();
        });

        $(".btnEditar").bind("click", function () {
            operacao = "E";
            indice_selecionado = parseInt($(this).attr("alt"));
            var cli = JSON.parse(tbClientes[indice_selecionado]);
            $("#aviso").val(cli.Aviso);
            $("#aviso").focus();
        });

        $(".btnExcluir").bind("click", function () {
            indice_selecionado = parseInt($(this).attr("alt"));
            Excluir();
            Listar();
        });
    });
</script>
  • 1

    The problem with cookies is that they are individual per customer, not that you need a database but you will need some logica server side to redistribute the information.

  • Is there any other way than javascript that I can do this ?

  • 1

    Ué, you can send the warning to your backend that keeps in memory along with the date and time that the warning was received, all people requesting the warnings, for example on GET /avisos only receive recent warnings (and you appropriately discard old warnings). The problem with you not using a BD is that in case your server crashes you lose the messages, and in case you have a cluster you will still need to implement a logic to redistribute the warnings between your servers.

  • You can use mongodb collections with TTL too! But only if you are already using Mongodb, otherwise it would be Overkill.

  • I use Asp.net mvc with sql server express 2012. I didn’t put the question to tag because I didn’t think it would be necessary. :(

  • If I’m not mistaken. net has the scope of application, who knows you do not store the messages there and implements the deletion logic of the older messages...

  • 1

    Then I’ll add the tag of Asp.net mvc. Maybe this way I can get an enlightening answer right ?

  • 1

    You may consider storing this information through the API localStorage, with Javascript only. "Consider" because, as stated by you "would be several warnings" and localStorage has storage limit.

  • But it wouldn’t be that heavy. It would be too few warnings. Would I have put a code response using my scenario ?

  • @Erikthiago and if the user closes the window you want everything to start again? or closing and opening again you want the 3 hours to be counted?

  • I want even closing the window to continue there, counting the 3 hours. To make it simpler.

Show 6 more comments

1 answer

0


You can use localStorage for this purpose, example:

Take the datetime and store it in a variable, enter it in the localstorage.

To set the value, use setItem.

var horas = '1 hora';

localStorage.setItem('aviso1', horas);

To get the value, use getItem

localStorage.getItem('aviso1');
result: '1 hora'

Edited with an example code:

function criarAviso(){
 //pega o horario atual
 var data = new Date().getHours();
 //adiciona mais 3 horas 
 var aviso = data + 3;

 //setou o aviso
 localStorage.setItem('aviso 1', aviso);

}

//pega a hora atual
var dataagora = new Date().getHours();

//pega o aviso
var verificar = localStorage.getItem('aviso 1');

//faz o parse para número
verificar = parseInt(verificar);

//compara o horario
if(verificar <= dataagora){
  //cria a ação para o usuario;
}

Take this create.

  • I understand, but how can I use the localSotrage on a page Razor ? How can I play this value and pick up and show on an html page ? If possible ?

  • It is possible to render pages with some js scripts?

  • Yes yes, no problem. I need to save this warning for a few hours. If scripts work, great !

  • Okay, you need to take the current browser date to store in the Log, and compare for each user update, if the value that was stored is still higher than the current one. There is no worker working in the background in the browser to delete this data. You can check, if you pass the time, warn the user and delete this warning

  • Could put in code ?

  • Okay, I put the code

  • i made a code here(I’ll post it) and wanted to adapt it that part to expire. I would like ?

  • Use the window.setTimeout(closeWidth, time), the time is the amount of seconds that will trigger the function closeWidth. Each second in time equals 1000 ms, so you get to three hours. You need to multiply by 60 which are the seconds, plus 60 which are the minutes and plus three which are the hours. In function closeWarnings, you close the set warnings.

  • Man, could you code that too? It gets a little confusing talking like that. If you could it would be great !

Show 4 more comments

Browser other questions tagged

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