I am trying to fetch book rows by books’ first letter with jquery $.post into my <td> </td> which is part of my table.
My table looks like :
<table id="myTable">
<thead>
<tr>
<th class="page">pages</th>
<th class="book_name">Book Name</th>
<th class="author">Author</th>
</tr>
</thead>
<tbody id="result_list">
<!--Here is data which will come with ajax($.post) -->
</tbody>
</table>
Writing jquery code, I become successful but with $("#result_list").html(data) like this:
$.post( "/ajax.php", { book_first_letter: 'A'},
function( data ) {
$( "#result_list" ).html( data );
}
);
But I dont want to fetch all data as HTML and insert into <tbody> . I want to fetch data from ajax.php as separate variable. For example; book_name,logo,pages,author. And I want to insert them into <td> </td>.
My ajax.php is like this:
$letter= trim($_POST['book_first_letter']);
$query = $this->book_model->get_books_by_letter($letter);
foreach ($query as $book) { ?>
<tr>
<td> <?php echo $book->page; ?> </td>
<td> <?php echo $book->name; ?> </td>
<td> <?php echo $book->author; ?> </td>
</tr>
<?php
}
?>
Is there any way to take each variable(i.e. $book->name) and insert it into <td></td> ?
Not only can you, but you should.
Rather than having PHP return html as text, have it return a JSON object.
You’re going to need to do a few things.
First add a fourth argument to your $.post() call for a dataType of “json”.
Then, its good form to have PHP send JSON headers for the result so before you send out any data in PHP use
And rather than echoing out the properties of your book model, just use json_encode()
So the client now has the raw data and you can use js/jQuery to loop through the books and add it to your table.