Curious2learn Curious2learn - 1 month ago 5
Ajax Question

Using jquery .load to add rows to an html table

The code below adds the

html
returned by
returndatafromdb2()
function in the server to the table that has id
resultstable2
. The html returned by the function
returndatafromdb2()
is of the form:

"<tr><td>some text</td><td>more text</td></tr><tr><td>some text</td><td>more text</td></tr><tr><td>some text</td><td>more text</td></tr>"


As you can see in the code I am using
.load()
from jquery to obtain the
html
from the server and add it to the table. The code I am using, however, replaces the existing rows in the table instead of adding to it. How can I use jQuery
.load()
function to add the rows to existing rows and not replace them?

If I can somehow assign the html received from the
.load()
function to a variable say
newhtml
, I can do something like
$(newhtmltext).appendTo('#resultstable2')
. But I don't know how to assign the html obtained by
.load()
to a variable, or to use it as a string.

Thanks.

The Code:

Create table using jquery



<p>Method 2</p>

<table id="resultstable2">
<tr>
<th>Grade</th>
<th>Price</th>
</tr>
</table>

<button id="b2">Execute returndatafromdb2()</button>

<script type="text/javascript">

$.ajaxSetup({
cache: false
});


var getdata2 = function(){
var loadurl2 = "{{=URL('default', 'returndatafromdb2')}}";
$('#resultstable2').load(loadurl2));
};

$('#b2').click(getdata2);

</script>

Answer

There isn't a way to do it with the load() function. You will want to use the normal ajax calls and write your own callback function. Something like this:

var getdata2 = function() {

    var loadurl2 = "{{=URL('default', 'returndatafromdb2')}}";
    $.get(loadurl2,function(data){
        $('#resultstable2').append(data);   
    },'html');

};

$('#b2').click(getdata2);
Comments