I have a web site which enables user to add or delete their own favorite books. I added “add” and “delete” button every row in page. I can add favorite books in session array and there is no problem about it. But I can not delete a row from “user’s favorite book list.”
I used jquery, ajax. I could unset row but what I want is delete that row from session completely and order again. Despite the fact that I unset the row, element number of session does not change.
Here is code :
//There are rows in $newdata. That is to say, newdata array is not empty now.
// I just add newdata array here to show that there is an array called newdata.
var $newdata = array();
function delete_row($rowid) {
if (isset($rowid)) {
$this->newdata = $this->session->userdata('contents');
unset($this->newdata[$rowid]['id']);
unset($this->newdata[$rowid]['name']);
unset($this->newdata[$rowid]['author']);
unset($this->newdata[$rowid]['year']);
$this->session->set_userdata(array('contents' => $this->newdata));
$contents = $this->session->userdata('contents');
$i = 0;
foreach ($contents as $key)
{
if ($key['id'] != "") {
$i++;
$this->newdata[$i]['id'] = $key['id'];
$this->newdata[$i]['name'] = $key['name'];
$this->newdata[$i]['author'] =$key['author'];
$this->newdata[$i]['year'] =$key['year'];
} else {
}
}
$this->session->set_userdata(array('contents' => $this->newdata));
} else {
echo "There is no row to be deleted";
}
}
Here is view code(html) :
<div>
<?php
if (count($contents)==0) {
echo 'There is no favorite book';
} else {
echo '<table class="table table-striped">';
$i = 0;
echo count($contents);
foreach ($contents as $items) {
echo '<tr>';
echo '<td>'.$items['id'].'</td>';
echo '<td>'.$items['name'].'</td>';
echo '<td>'.$items['author'].'</td>';
echo '<td>'.$items['year'].'</td>';
echo '<td><button id='.$i .' class="delete_row"><b>DELETE</b></button></td>';
echo '</tr>';
$i++;
}
echo '</table>';
}
?>
</div>
Here is jquery code :
$('.delete_row').click(function(event) {
event.preventDefault();
var id = $(this).attr("id");
window.location.href = '/favorite/delete_row/'+id;
});
I think the problem lies in the del button id. You’re using the
$ivariable instead of$items['id']. So the JS redirect will send the count int and not the itemidto the delete page.Change:
Into: