I am trying to delete the element with post jquery request:
$(function(){
//The element
// <a data-id="39" data-toggle="modal" href="#delete"><i class="icon-trash"></i>
Delete</a>
$('.delete').on('click',function(){
var id= $(this).attr('data-id');
$.post('task/delete', { id: id }, function(data) {
alert('Task deleted!');
})
.success(function(){ alert('Task deleted!'); })
.complete(function(){ alert('Task completed!'); })
.error(function(){ alert('Error was found!'); });
})
});
My controller is called task and the function inside it is called delete.
class Task extends CI_Controller {
public function delete()
{
$this->load->model('tasks_model','task_delete');
$this->task_delete-> deleteTask($_POST['id']);
}
}
The model is quite simple.. it simply deletes the record.
public function deleteTask($task_id)
{
$task_id = mysql_real_escape_string($task_id);
$this->db->query("DELETE FROM tasks WHERE task_id = ?", array($task_id));
}
I get two messages..one is error and one is delete…
Another thing that I want to avoid is someone posting the id to the controller task .. which will delete the records one by one automatically, is there a way to avoid this too?
Your controller method should look something like this
And you models method like this
As I would recommend validating the user where the comment says you should, and using CI’s active record library where you can to increase portability to a different DB.
Edit
To show PHP errors (and maybe MySQL errors if they are turned on).
To ensure the task is deleted, do this (which is not as efficient).
And then do something with the returned boolean in the controller.