Total Javascript calculation

1

Hello, this is the code that calculates my shopping cart, it works perfectly, but when you refresh the page in the browser, it returns to the starting price. That is, if you add 2 products it displays right, but when there is a browser refresh, it returns to an amount, how can I solve it?

  $(document).ready(function (e) {
    $('input').change(function (e) {
        id = $(this).attr('rel');
        $index = this.value;
        $preco = $('font#preco'+id).html().replace("R$ ",'');
        console.log($preco);
        $val = ($preco*$index).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');;
        $('font#sub'+id).html('R$ '+$val);
          });
        });
    
asked by anonymous 03.02.2016 / 15:20

1 answer

0

Javascript is interpreted and executed by the browser and with each new run of the browser the javascript is reloaded with its default values.

How to save the data and even with refresh get the values again?

  

Session is a feature that allows you to save values (variables) to be used throughout the user's visit. Saved values in the session can be used anywhere in the script, even on other pages of the site. They are variables that remain set until the visitor closes the browser or the session is destroyed.

Javascript:

...
    <script> 
    localStorage.setItem('chave','valor');

    alert(localStorage.getItem('chave'));
    </script>
...

PHP:

You need to log in before you can seize or retrieve values from it. There is no limit to the values saved in the session. The session is personal to each visitor. When a visitor accesses the site, a cookie is generated on their computer by reporting a unique session id, and PHP uses that identifier to 'organize' sessions between visitors to your site. But this cookie is valid only while the browser is open.

  • To open the session, just use this command in PHP:

..

<?php
session_start(); // Inicia a sessão
  • Once the session is started you can define values inside it like this:

..

<?php
$_SESSION['preco'] = 100;
  • And when you need to display the value saved in the session (probably on other pages), just do this:

..

<?php
echo $_SESSION['preco']; // Resultado: 100
  • You can save as many values as you want, you can re-define the values and use them in echos, function arguments and whatever way you prefer. To delete a specific session variable you use unset ():

..

<?php
unset($_SESSION['preco']); // Deleta uma variável da sessão
  • You can also destroy the entire session at once by deleting all the variables saved in it: -

..

<?php
session_destroy(); // Destrói toda sessão

Official Documentation:

Function session_start () »Sign in

Function unset () »Delete a PHP variable

Function session_destroy () »Destroys an entire session and its variables

    
03.02.2016 / 20:03