0

I'm writing a code to compare the result of getJson by capturing its result from a previous data. But I'm not sure where to put the correct code?

Result of data:

enter image description here

Sample code:

var prevData = JSON.stringify("");
function startRefreshTable() {
$.getJSON('/tablestatus/', function(data) {

    if (data !== prevData){
        //perform something here
    }
    prevData = data;
}

Thanks

iamcoder
  • 519
  • 2
  • 4
  • 21

1 Answers1

1

You can't compare a JSON string to a JavaScript object. You need to JSON.stringify both results.

Since you already stringified your prevData variable, you also need to stringify the data variable: JSON.stringify(data) !== prevData.

Here's the complete code:

var prevData = JSON.stringify("");
function startRefreshTable() {
$.getJSON('/tablestatus/', function(data) {

    if (JSON.stringify(data) !== prevData){
        //perform something here
    }
    prevData = data;
}
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Koby Douek
  • 15,427
  • 16
  • 64
  • 91
  • Do you mean "compare a JavaScript object to JSON"? Otherwise I don't know what "a JSON that was not" means. JSON can only exists inside strings in JavaScript. – Felix Kling Aug 28 '17 at 05:14
  • @FelixKling thanks. Gotta get better at expressing myself in English. – Koby Douek Aug 28 '17 at 05:18