MasterGberry
MasterGberry

Reputation: 2860

Issue with JSON stringify?

/* Helper function to clean up any current data we have stored */
function insertSerializedData(ids, type) {
    // Get anything in the current field
    current_data = $('#changes').val();
    if (!current_data) {
        var data = new Array();
        data[type] = ids;
        $('#changes').val(JSON.stringify(data));
    } else {
        var data = JSON.parse($('#changes').val());
        data[type] = ids;
        $('#changes').val(JSON.stringify(data));
    }
    console.log($('#changes').val());
}

I am using the following function to either add data to a current JSON object or create a new JSON object all together to be used in PHP later. Is the stringify() method only for FF? I am using google chrome and I am being given an empty object when using the conosole.log() function...

Also what happens if you try to store two values with the same key? I assume it will overwrite...so I should add a random math number at the end array in order to keep duplicates from showing up?

Thanks :)

Upvotes: 0

Views: 2597

Answers (2)

Tim Christensen
Tim Christensen

Reputation: 381

I reformatted it a bit, but and this seems to work. It will set the "value" attribute of the #changes element to a JSON string. I assume that the type argument is supposed to be the index of the array which you're trying to assign?

function insertSerializedData(ids, type) {
  var changes = jQuery('#changes'), arr, val = changes.val();
  if (!val) {
    arr = [];
    arr[type] = ids;
    changes.val(JSON.stringify(arr));
  } else {
    arr = JSON.parse(val);
    arr[type] = ids;
    changes.val(JSON.stringify(arr));
  }
  console.log(changes);
}

Upvotes: 0

raina77ow
raina77ow

Reputation: 106385

These lines may cause problems:

var data = new Array();
data[type] = ids;

... because arrays in JavaScript are not quite like arrays in PHP. I suppose what you meant is better expressed by...

var data = {};
data[type] = ids;

Besides, current_data seems to be local to this function, therefore it also should be declared as local with var. Don't see any other problems... except that similar functionality is already implemented in jQuery .data() method.

UPDATE: here's jsFiddle to play with. ) From what I've tried looks like the array-object mismatch is what actually caused that Chrome behavior.

Upvotes: 2

Related Questions