Refresh without losing data, is it possible?

Asked

Viewed 1,403 times

0

The code below allows the user to enter a comment that is returned by the ajax callback to the same page. There is a way via javascript or php that to upgrade the page the inserted comments are not lost?

AJAX.php

<!DOCTYPE html>
<html>
    <head>
        <title>AJAX</title>

        <style>
            .comments{
                margin-left:400px;
                width: 400px;
            }
        </style>         
    </head>
    <body>
        <div class="cadastro"> 
            <form id="form-msg" method="post" enctype="multipart/form-data">
                <fieldset>
                    <p>
                        <span>Digite seu comentário:</span>
                        <input type="textbox" id="mensagem">
                        <button type="submit" id="enviar"> Clique  </button>
                    </p> 
                </fieldset>
            </form>   
        </div>     
            <p>Comentários</p>
            <span id="aqui"></span>     
        </div>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="ajax.js"></script>
    </body>
</html>

AJAX_ACTION.php

<?php

$mensagem = $_REQUEST['mensagem'];

echo "Vem do callback: " . $mensagem;

AJAX.js


$('#form-msg').submit(function(e){
    e.preventDefault();

    if($('#enviar').val() == 'Enviando...'){
        return(false);
    }
    var mensagem = $('#mensagem').val()
    if (mensagem == ''){
        alert("Comentário não pode ser vazio")
    }
    else{
        $.ajax({
            url: 'ajax_action.php',
            type: 'post',
            dataType: 'text',
            data: {
                'mensagem': $('#mensagem').val()                
            },
            success:  function(mensagem){
                $("#aqui").append("<br>").css("color", "red").append(mensagem)
            },              
            complete:  function(){
                $("#mensagem").val('')
            },             
        }); 
    }
});

  • Are you using some kind of database to persist the information?

  • You will need to persist this information somewhere as a database, for example.

  • So without the awkward database?

  • Peter try to explain BETTER what you need, because we have already had this question held on the site.

  • With JS you use a cookie. Search by localStorage.

  • Is there a way via javascript or php that when updating the page the inserted comments are not lost? You are not using database for this?

  • 2

    @Pedrohenrique, it is even possible to do without database, using local Torage or some cookie but would be visible only to the person who sent the comment... otherwise you write these comments somewhere else, as in a text file on the hard drive. But it’s much more work and it doesn’t make any sense in a real application because the databases are there for it... Without storing the information somewhere, you can’t get it back..

  • Take a look at the HTML layout. @Pedrohenrique wants comments to be attached to the page just like blog comments. Pedro, if so, only with php and database.

  • 1

    Possible duplicate of Ajax does not send data to php!

  • @Leandroalfredo I do not believe that this is a duplicate, the code of the questions is the same but the question itself is different. I wonder if the comments inserted in html via javascript could remain there when updating the page, without database use.

Show 5 more comments

1 answer

1

For those who may be interested, it follows the way to store the comments in the browser’s location and not lose them with a simple refresh on the page. Even the Storage location allows data to be saved even after closing the browser.

In the AJAX.js file we insert the function to load the information (comments) with a loop. We also insert a try catchto alert the user if your browser does not allow data storage.

$(document).ready(function () {
    try {
        if(window.localStorage){
            if(localStorage.getItem(1) !== null){
                for (var i = 1; i <= localStorage.length; i++) {               
                    $("#aqui").append("<br>").append(localStorage.getItem(i))
                    console.log(localStorage.length)
                }  

            }       
        } 
    } catch(e) {
        alert("O seu navegador não permite salvar dados localmente, isso pode afetar a sua experiência com o site!");
    }   
});

In the same file we create a global variable to store the value of the last storage index because in Ajax we will always need the last index + 1 in the insertion in the Storage location.


var key = 0;    

Finally in Ajax, in the negotiations Success we received comments that is variable mensagem and add it to the last +1 index

$('#form-msg').submit(function(e){
    e.preventDefault();

    if($('#enviar').val() == 'Enviando...'){
        return(false);
    }
    var mensagem = $('#mensagem').val()
    if (mensagem == ''){
        alert("Comentário não pode ser vazio")
    }
    else{
        $.ajax({
            url: 'ajax_action.php',
            type: 'post',
            dataType: 'text',
            data: {
                'mensagem': $('#mensagem').val()                
            },
            success:  function(mensagem){
                $("#aqui").append("<br>").append(mensagem);
                //Inserção no local storage
                key++;
                localStorage.setItem(key, mensagem);                

            },              
            complete:  function(){
                $("#mensagem").val('')
            },           
        });      
    }
});

Remember that existing content in your local Store can be viewed in the case of Chrome in Devtools > Application > Storage > Local Storage

Browser other questions tagged

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