montreal
montreal

Reputation: 35

Delete Objects of localStorage after AJAX Success

// Edit

Thanks for all the help so far. I'm afraid, I did pretty much wrong, so I re-structured the whole code als also the "structure" of the localStorage Array

Here's my full code and the intention behind it. I want to check for connectivity (for which I use pingjs.js) and if there's no connectivity, the user input gets stored in the localStorage. If we get a ping back, we upload everything in the localStorage through jQuery AJAX and delete this submitted data (not everything which came after, for example) from the localStorage Array. The thing is also, that I want to avoid duplicates (update already existing data based on stnr AND pstn) and also get something like a unique id for indexing the localStorage Array.

So far this is my code with exception of the indizes and the updating of already existing stnr AND pstn:

<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/pingjs.js"></script>
<script>
    $(document).ready(function() {
        $('#store').click(function() {
            var startnummer = $("#startnummer").val();
            var ergebnis = $("#ergebnis").val();
            var position = $("#position").val();

            var data = [
                {
                    "stnr": startnummer,
                    "rslt": ergebnis,
                    "pstn": position
                }
            ]

            /*  
                So far I use localStorage.length for indexing, but
                I want something for checking of duplicates and update
                them if necessary, based on stnr AND pstn, so if these
                are same, only update rslt
            */
            localStorage.setItem((localStorage.length), JSON.stringify(data));
        });

        //  We got a ping
        ping('https://example.com/').then(function(delta) {
            if(window.localStorage !== undefined) {
                var fields = $(this).serialize();

                $.ajax({
                    type: 'POST',
                    url: 'xyz.php',
                    data: fields,
                    success: function(html){
                        //  Here I want to delete all the passed data
                        localStorage.removeItem( ??? );

                        //  Output status
                        $('#status').fadeIn(500).delay(5000).fadeOut(500).html(html);
                    }
                });
            } else {
                alert("Storage Failed. Try refreshing");
            }   
        //  We have no ping
        }).catch(function(err) {
            alert('Could not ping remote URL', err);
        });
    });
</script>

The storing works without problems. So no problem here.

Upvotes: 0

Views: 1018

Answers (2)

comu
comu

Reputation: 921

It seems like you may not understand localStorage API completely. I would suggest reading localStorage from MDN.

The first problem is it seems like you may be storing the information in localStorage incorrectly. Local storage is key based. This means that all data is located in local storage via a key. For instance {"key" : "data"}.

A side note, data in local storage is kept as a string. So in order to read/write data to/from local storage you need to stringify/parse it.

To continue on your question, I am under the impression you are saving that entire array in localStorage, and then trying to remove each key inside of the array. As stated before, this wont work, for a few reasons. Firstly, you cannot use the localStorage.removeItem() method to remove an object stored because the object is actually a string and not parsed. Secondly, even if it wasn't saved as a string, the function doesn't operate on the storage data, but on the key the data was stored under. What your code is missing, which would help greatly, is the way you are saving in localStorage in the first place. Because in this case you would not even have to call removeItem() three times, just call it once on the key it's all stored under. Let me give an example I think may relate to your question:

var data = [
  {
    "id": 1,
    "name" : "Joe"
  },
  {
    "id": 2,
    "name": "Peter"
  }
]

//Setting the data to localStorage under the key "people"
localStorage.setItem("people", data);

// ... inside your ajax function
 ...({

  //Remove whole array of data based on key

  localStorage.removeItem("people");
  
  //All done with removal
  
  //Rest of your code
 })

IF you would like the delete just those specific keys in localStorage, you're going to either have to save them separately (recommended), or you're going to have to read, parse, edit, resave (not recommended) the data every time you want to do that.

Upvotes: 3

michaelitoh
michaelitoh

Reputation: 2340

Call removeItem function passing the key of the data you want to remove.

$.ajax({
    type: 'POST',
    url: 'xyz.php',
    data: {
        results: resultobj
    },
    success: function(callback){
        // Delete data from staticLS here
        localStorage.removeItem("tmemberData")
        // Output message of callback status
        $('#status').fadeIn(500).delay(5000).fadeOut(500).html(callback);
    }
});

Upvotes: 0

Related Questions