2

I am new to jQuery!

I am having one table which load data from server using ajax\jQuery on every x seconds, data receiving in JSON format, My problem is that I want to update only particular cell if value is changed or new.. How do I compare old data with new data as new data are coming in JSON format and old data reside in tables.....

Here is my code:

window.setInterval(function() { 
    // this code will execute on every 5s 
    // so we could send an AJAX request to verify if we 
    // have new data. Example with jQuery: 
    $.getJSON('/foo', { }, function(result) { 

    }); 
}, 5000);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nidhi
  • 201
  • 2
  • 6
  • 13

2 Answers2

2

Use .data

window.setInterval(function() { 
    $.getJSON('/foo', { }, function(result) { 
        //Get the old data stored in the body using jquery data
        var old_data = $('body').data('my_data');
        //If objects are not the same, update cell
        if ( ! equal_objects(result, old_data) )
             update_cell();
        //Store the new data
        $('body').data('my_data',result);
    }); 
}, 5000);

OBS: equal_objects is a function you should implement to compare 2 objects since JavaScript doesn't provide this functionality. See this post for details: Object comparison in JavaScript

Community
  • 1
  • 1
Frias
  • 10,991
  • 9
  • 33
  • 40
0

Add an unique ID to your td tags

<td id="tdname">200</td>

if(document.forms[0].getElementsByTagId("tdname").innerText != data[0].value){
    document.forms[0].getElementsByTagId("tdname").innerText == data[0].value;
}

Something like that, now just loop through all your data and update one by one.

Timothy Martens
  • 678
  • 4
  • 17
  • On page load this table in dynmically genrated once after that every 5 seconds table need to be updated if there any changed in data then only that cell needs to updated.. I cannot add the id to table column.. – Nidhi Dec 09 '11 at 16:07
  • I guess I would need to see the way the code is generated. Could you post that here? Also you can't modify the way the code is generated? Should be simple. – Timothy Martens Dec 09 '11 at 16:48