0

I am trying to make sure the data i got from an ajax is passed onto my view. I actually got success with that but on page refresh the data disappears. Here is my jquery code

$(document).ready(function(){

    $('#Item').hide();

    $('#submitButton').hide();

    $("#cartIcon").click(function(){

    var id = $('#id').val();

    console.log(id);

    $.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
        type: 'POST', // Type of response and matches what we said in the route
        url: '/addtocart/', // This is the url we gave in the route
        dataType: 'JSON',
        data: {'id' : id}, // a JSON object to send back
        success: function(response){ // What to do if we succeed
            $('#subtotal').html(response.totalPrice); 
            $('#total').html(response.totalPrice);
            $('#Item').show();
            $('#noItem').hide();
            $('#submitButton').show();
        }
    });
  });
});

How do i make my .html response remain after page reload

Patrick Obafemi
  • 908
  • 2
  • 20
  • 42

2 Answers2

1

Save the data into a cookie or local storage. Every time the page loads, you'll need to check if there is some data in the local storage to show.

Alexis88
  • 297
  • 1
  • 11
1

as they mentioned, you could use LocalStorage:

$(document).ready(function(){

    $('#Item').hide();

    $('#submitButton').hide();

    function load_data(){
        var current;
        current = localStorage.getItem("cartData");
        if(current == null || current == undefined){
            return ;
        }
        current = JSON.parse(current);
        $('#subtotal').html(current.totalPrice); 
        $('#total').html(current.totalPrice);
    }

    load_data();

    $("#cartIcon").click(function(){

    var id = $('#id').val();

    console.log(id);

    $.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
        type: 'POST', // Type of response and matches what we said in the route
        url: '/addtocart/', // This is the url we gave in the route
        dataType: 'JSON',
        data: {'id' : id}, // a JSON object to send back
        success: function(response){ // What to do if we succeed
            $('#subtotal').html(response.totalPrice); 
            $('#total').html(response.totalPrice);
            localStorage.setItem("cartData",JSON.stringify({"totalPrice":response.totalPrice}));
            $('#Item').show();
            $('#noItem').hide();
            $('#submitButton').show();
        }
    });
  });
});
Salar
  • 91
  • 4