Dynamically updating a table row using AJAX

Freeloader picture Freeloader · Apr 24, 2012 · Viewed 12.3k times · Source

Normally, I'm a big stickler for jfGit, but I've been looking all over the web and can't get this code to work.

My setup:

  • index.php - a page containing a table populated by data from a mysql database.
  • update.php - a php script able to output a table row in html

Intention

What I want to do: by clicking on a link or button, a specific table row is updated.

Current solution

This is the code as I tried it so far.

Ajax/jQuery code, right under the body tag (is that the right location?):

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('a.pop').click(function() { 
var popID = $(this).attr('rel');
$.ajax({
        url: 'update.php',
        method: 'GET',
        data: 'userID=' + popID,
        success: function(returnData){
             $(popID).html(data);
              $(popID).dialog();
              alert('Load was performed.');
        }
    });
});
});
</script>

And the table code (printed using php):

echo "<div id=\"$ID\">";
// all tr + td from table
echo "<td><a href=\"#\" id=\"clickingEvent\" class=\"pop\" rel=\"$ID\">Update</a></td>\n";
echo "</tr>\n";
echo "</div>";

Result

Currently, I don't get any result at all, AJAX isn't even loading the php page. After I click the update button, nothing happens.

Any help would be greatly appreciated, thank you in advance :)

EDIT:

The partial solution

The Ajax part of the code now properly works, thanks to all for your input!

What happens now though is that it adds a NEW row in front of the table tag, and the old row remains. When I take a look at the generated source it says that there's a new row with the div id of 'popID' that I specified. Scrolling down, it appears that the div tag of the old row was removed.

Any way I could solve that?

Answer

Bernat picture Bernat · Apr 24, 2012

Note that you should add the retrieved data into popID. The correct way is modifying your function to:

$.ajax({
        url: 'update.php',
        method: 'GET',
        data: 'userID=' + popID,
        success: function(new_data){
             $(popID).html(new_data);
              $(popID).dialog();
              alert('Load was performed.');
        }
    });

Note that returnData now is new_data, and you append it with the same name