Reputation: 499
I am trying to use jquery ajax to delete some data specifically ingredients of a recipe and I am using the CodeIgniter framework but it fails. Here is the parts of my code:
$(".delete").live('click',function()
{
var ri_id = $(this).attr('id');
if(confirm("Are you sure you want to delete this ingredient? Action cannot be undone."))
{
var r_id = "<?php echo $this->uri->segment(3); ?>";
alert(ri_id +" " +r_id);
$.ajax({
type: "POST",
url: "/ingredient/delete",
data: "ri_id="+ri_id +"&r_id=" +r_id,
success: function(){
$(this).parent().parent().parent().remove();
},
failure : alert('fail')
});
Then here is my ingredient.php:
class Ingredient extends CI_Controller {
function delete()
{
$data['ri_id']= $this->input->post('ri_id');
$data['r_id']= $this->input->post('r_id');
if (!empty($data['id']))
{
$this->load->model('ingredient_model', '', TRUE);
$this->ingredient_model->delete_recipe_ingr($data);
$this->output->set_output('works');
}
else
{
$this->output->set_output('dontwork');
}
}
}
and my model:
class Recipe_model extends CI_Model
{
public function delete_recipe_ingr($data)
{
$this->db->where($data);
$this->db->delete('st_recipe_ingredients');
}
}
Did I miss something or is it my code that is wrong? I would really appreciate your help. Thanks in advance.
Upvotes: 0
Views: 83
Reputation: 434695
My first guess is that this
isn't what you think it is right here:
success: function(){
$(this).parent().parent().parent().remove();
},
From the fine manual:
context
This object will be made the context of all Ajax-related callbacks. By default, thecontext
is an object that represents the ajax settings used in the call ($.ajaxSettings
merged with the settings passed to$.ajax
).
So inside your success
callback, this
is pretty much a simple object rather than something in the DOM.
There are two standard solutions. You could save a reference to this
and use that:
var self = this;
$.ajax({
// ...
success: function() {
$(self).parent().parent().parent().remove();
},
// ...
or use the context
option to $.ajax
:
$.ajax({
// ...
context: this,
success: function() {
$(this).parent().parent().parent().remove();
},
// ...
And, of course, fix up the failure
stuff as discussed in the comments.
Upvotes: 1