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
  • 529
  • 2
  • 4
  • 23

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
  • 795,719
  • 175
  • 1,089
  • 1,143
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
  • 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