DanceSC DanceSC - 4 months ago 7
Javascript Question

Compare php array to javascript array same data

Scenario: I need to compare a database cell on the page load (php) against itself in an interval loop every x amount of minutes for changes.

My Initial load data looks like this:

var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data3); ?>);


So on page load, I save the cells into a javascript variable with a "~|~" delimiter, where $data1, $data2, and $data3 are 3 different cells in the database (arrays of data).

And my interval loop data (ajax call) looks like this:

// PHP on the AJAX page
echo json_encode($data1)."~|~".json_encode($data2). "~|~".json_encode($data3);

// AJAX code that gets called every x Intervals
$.get("ajaxpage.php", function(data) {
if (data == olddata) {
console.log("Good!");
}
});


When I compare
olddata
against
data
they look almost identical except... data that has a
/
in it will look like
\/
in the
data variable and not in the
olddata` variable.

Example:

"10":["10"],"11":["11 5\/25"] // data = return from the AJAX call
"10":["10"],"11":["11 5/25"] // olddata = what was originally echoed on page load.


How can I compare the two so that they will match perfectly? So that what I echo from the database and json_encode, will line up with what I get from the exact same thing echoed on a page and jason encoded from the json function return.

Note: If I remove the JSON.stringify then it will return [object Object]

Answer

You're using a very bad practice. Just use AJAX to get this:

var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" + 
JSON.stringify(<?php echo json_encode($data3); ?>);

And store "olddata" in a JavaScript Global var, then compare the old data with the new data returned by $.get. This isn't the solution for your bug, but it's a better way to do what you're doing.

To fix the bug just declare the type of the return value in the your $.get function, like that:

$.get("ajaxpage.php", function(data) {
    if (data == olddata) {
         console.log("Good!");
    }
}, 'text');

For more information about the return type, look the jQuery Documentation: jQuery $.get Documentation

Comments