jQuery ajax only works first time
- by Michael Itzoe
I have a table of data that on a button click certain values are saved to the database, while other values are retrieved. I need the process to be continuous, but I can only get it to work the first time.
At first I was using .ajax() and .replaceWith() to rewrite the entire table, but because this overwrites the DOM it was losing events associated with the table. I cannot use .live() because I'm using stopPropagation() and .live() doesn't support it due to event bubbling. I was able to essentially re-bind the click event onto the table within the .ajax() callback, but a second call to the button click event did nothing.
I changed the code to use .get() for the ajax and .html() to put the results in the table (the server-side code now returns the complete table sans the <table> tags). I no longer have to rebind the click event to the table, but subsequent clicks to the button still do nothing.
Finally, I changed it to .load(), but with the same (non-) results.
By "do nothing" I mean while the ajax call is returning the new HTML as expected, it's not being applied to the table. I'm sure it has something to do with altering the DOM, but I thought since I'm only overwriting the table contents and not the table object itself, it should work. Obviously I'm missing something; what is it?
Edit:
HTML:
<table id="table1" class="mytable">
<tr>
<td><span id="item1" class="myitem"></span>
<td><span id="item2" class="myitem"></span>
</tr>
</table>
<input id="Button1" type="button" value="Submit" />
jQuery:
$( "Button1" ).click( function() {
$( "table1" ).load(
"data.aspx",
function( data ) {
//...
}
);
} );