How to Send Data from localStorage via AJAX to PHP and save them to an HTML file

Asked

Viewed 126 times

0

I want to send the data saved in Localstorage with PHP to a file or to a database not necessarily need to be PHP code need some solution for this

<h2>Likes</h2>

<p id="demo"></p>
<button name="clique" class="btn btn-primary" id="like" type="button">
Likes <span class="badge" id="likeQt"> 0 </span>
</button>
<p id="date" style="display: none;">Data e horário do último like: <span id="dateLike" ></span></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


<script>
 
    $().ready(function(){
 
    atualizarSpan();
    function dadosClick(){
    if(typeof(localStorage)){
     let likes= '';
       if(localStorage.likes){
                    
       likes=JSON.parse(localStorage.likes);
                   
       likes={numberLike:Number(likes.numberLike)+1,date:Date()};
                 
       localStorage.likes=JSON.stringify(likes);
       console.table(JSON.parse(localStorage.likes));
                 
       atualizarSpan();
       }else{
                    
       likes={numberLike:1,date:Date()};
                  
       localStorage.likes=JSON.stringify(likes);
                   
       console.table(JSON.parse(localStorage.likes));
                  
       atualizarSpan();
       }
       }else{
       alert('Navegador não suporta localStorage.');
       }
       }
         
       function atualizarSpan(){
            
       if(localStorage.likes){
       var likeQt=JSON.parse(localStorage.likes);
          
       $("#date").show("slow");
       $("#dateLike").html(likeQt.date);
           
       $("#likeQt").html(likeQt.numberLike);
       }
       }
        
       $("#like").click(function(){
            dadosClick();
       });

    });
  
</script>

1 answer

0


Opa, then, I do not know if I understood very well your need, but for you to send this data saved in localStorage, or any other data, it is very simple using AJAX.

$.ajax({
    method: 'POST', // seu método pro backend
    data: { 
       dado: 'qualquer-dado',
       likes: localStorage.likes 
    }, // seus dados a serem passados, que podem ser o que você quiser
    url: 'seu-backend.php',
    success: () => alert('Dados enviados com sucesso!'), // só entra aqui se a requisição tiver sucesso
    error: () => alert('Algum erro ocorreu') // entra aqui se tiver algum erro, url errada etc
})

So you can send the data to your backend ai and make your entry in the database, etc....

There are also other ways if you do not want to use ajax, can put the localStorage data inside a form and give Submit, the possibilities are several.

I hope I’ve helped!!

  • Thanks! But How do I put inside the form and give Submit?

  • Let’s say you have a form, and in it an input expecting to receive that value, it’s simple: $('seu-input').value( localStorage.likes ), and ready, ta in your form. If you want it automatically without the need for the user to click on Ubmit, you can give a $(seu-form).submit(), but there is neither why not use ajax in my opinion

  • how do I receive the data there from the above code?

  • What data? If the localstorage, as I mentioned above, it’s just a matter of relating key and value and reading them in your backend

  • Yes are the localstorage wanted to know how could I catch them in the backend

  • Bro if you do what I said in the answer, you’ll be doing a POST/GET in the url you passed as parameter, and in the respective page in the backend is the same: $_POST['likes'] etc.. from there you can get them and do what you want

Show 1 more comment

Browser other questions tagged

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