Home Splicing and then saving json array via ajax
Reply: 1

Splicing and then saving json array via ajax

Todd Williams
1#
Todd Williams Published in 2018-01-12 16:34:24Z

I'm having trouble getting my json array to accept changes. I'm trying to remove an object from the array, and it appears to work but then when I look at the json array on the server it remains unchanged. What am I missing here?

Here is the function I'm using:

$(function() {
    $("#rectangle-delete").click(function() {

      var selection = $('#templateSelection > option:selected').text();

      var json = (function () {
        var json = null;
        $.ajax({
            'async': false,
            'global': false,
            'type': 'POST',
            'contentType':"application/json",
            'url': 'server/php/data/' + selection,
            'dataType': "json",
            'success': function (data) {
                json = data;
            }
        });
        return json;
      })();

      var ID_clicked = $(".rectangle.selected.targeted").attr('id');

      console.log('initial array is ' + json);

      json.some(function(e) {
        if (e.ID === ID_clicked) {

            var values = json.map(function(e) { return e.ID; });
            var index = json.map(function(e) { return e.ID; }).indexOf(ID_clicked);
            var data = JSON.stringify(json[index]);

            json.splice(index, 1);

            return true; // stop the array loop
        }
      });

      console.log('new array is ' + json);
    });
});

The console shows:

initial array is [object Object],[object Object],[object Object]

and then

new array is [object Object],[object Object]

but I'm still not changing the actual json file on the server.

Mic
2#
Mic Reply to 2018-01-12 16:51:57Z

When you pull down the json from the server you are not getting a reference to the object on the server but you are getting a copy of the data.

So you are just modifying data on your client.

To update the object on the server you should notify the change to the server (or reverse the logic letting the server do the computation and retrieve directly the result on the client).

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.387632 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO