Calculation of Javascript total

Asked

Viewed 117 times

1

Hello, this is the code that makes the calculation of my shopping cart, works perfectly, but when you update the page in the browser, it goes back to the initial price. That is, if add 2 products it displays right, but when there is a browser refresh, it goes back to a quantity, how can I resolve ?

  $(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);
          });
        });
  • Have you ever thought about using Cookies? generally this data is saved in server side session.

1 answer

0

Javascript is interpreted and executed by the browser and with each new execution of Browse 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 session values can be used in any part of the script, even on other pages of the site. 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 set or pick up values from it. There is no limit to values saved in the session. The session is personal to each visitor. When a visitor visits the site, a cookie is generated on his computer informing him of a unique session id and PHP uses this identifier to organize the sessions between visitors to his site. But this cookie is valid only as long as the browser is open.

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

..

<?php
session_start(); // Inicia a sessão
  • After logging in you can set values within it in this way:

..

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

..

<?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 Snippets, function arguments and the way you prefer. To delete a session-specific 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

Documentación Oficial:

Function session_start() » Start the session

Function unset() » Delete a PHP variable

Function session_destroy() » Destroys a whole session and its variables

Browser other questions tagged

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