xaisoft xaisoft - 1 year ago 77
JSON Question

Updated JSON object shows in DOM and local storage but not when accessed through the chrome developer console?

In the following js fiddle: https://dotnetfiddle.net/aNQEy3, I am initializing an object. When you click

, I am doing an ajax call and in the success call back I am updating the object with a new property and value. I can see the object updated in local storage as well as the DOM, but when I type it in the chrome console, I don't see the updated value. Here are more details:

Initialize the object:

<script type="text/javascript">

var localClientStorage = window.localStorage;

var cartObj = {"one":"1","two":"2"};




After this runs, I see the folowing:

Local Storage:

enter image description here


enter image description here


enter image description here

When I click the update function it runs the following code which gets the object from storage and adds a new value, but when I type "cartObj" into the console, it still shows the old value:

<script type="text/javascript">



url: '@Url.RouteUrl(new{ action="Update", controller="Home"})',

type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function() {

var localClientStorage = window.localStorage;

var cartObj = localClientStorage.getItem("cartObj");

cartObj = JSON.parse(cartObj);

cartObj.three = "3";

localClientStorage.setItem("cartObj", JSON.stringify(cartObj));





After clicking update, the LocalStorage and DOM show the updated value
, but the console only shows:

enter image description here

How can I show the updated value in the console? I tried updating the content inside the script element with something like this to see if refreshing it would work, but it didn't:

$("#cartObj").load(location.href+" #cartObj>*","");

In order to see the output, you have to select mvc-output-iframe in the console.

Answer Source

You have two variables cartObj. One global one created in your first snippet, which is the one you see in the console.

In your post callback you create another variable cartObj, which is local to the function scope and shadows the global one. It is destroyed once the function finishes execution. The global variable cartObj is not touched from the callback function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download