Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.remove() not working with ajax on success function

I have some html divs that are generated using jinja2 with this:

{% for student in students %}
<div class="item" id="{{ student.id }}_div">
   <div class="right floated content">
      <div class="negative ui button compact remove_from_class" id="{{ student.id }}">Remove from Class</div>
   </div>
   <i class="large user icon middle aligned icon"></i>
   <div class="content">
      <div class="header">
         <h3><u>{{ student.get_full_name }}</u></h3>
      </div>
      <div class="description">{{ student.email }}</div>
   </div>
</div>
{% endfor %}

This is the script I have for it which gets the parent divs id, and then tries to remove it using .remove().

$(".remove_from_class").each(function () {
$(this).on("click", function () {
    var id = this.id;
    var url = window.location.pathname.split('/');
    var set_id = url.pop() || url.pop()


    $.ajax({
        method: 'POST',
        url: '/ajax/delete_from_class/',
        data: {
            'id': id,
            'set_id': set_id,
        },
        dataType: 'json',
        success: function (data) {
            if (data.success == true) {
                var div_id = id + "_div";
                var parent_div = $(div_id);
                parent_div.remove();

            } else {
                alert("Student wasn't removed!");
            }

        }
    })
})
})

However the div isnt being removed, even though the success popup appears.

Thanks for any help!

like image 388
wtreston Avatar asked Oct 20 '25 15:10

wtreston


1 Answers

You need to use # to use id as a selector.

var div_id = "#"+id + "_div"; // Use # here
var parent_div = $(div_id);
parent_div.remove();

Or the better approach I would suggest here is to store div inside .click in some variable and then later use that.

$(".remove_from_class").each(function () {
$(this).on("click", function () {
    var $parentDiv = $(this).closest(".item"); // Save it here
    var id = this.id;
    var url = window.location.pathname.split('/');
    var set_id = url.pop() || url.pop()


    $.ajax({
        method: 'POST',
        url: '/ajax/delete_from_class/',
        data: {
            'id': id,
            'set_id': set_id,
        },
        dataType: 'json',
        success: function (data) {
            if (data.success == true) {
                $parentDiv.remove(); // And remvoe it here

            } else {
                alert("Student wasn't removed!");
            }

        }
    })
})
})
like image 190
void Avatar answered Oct 23 '25 04:10

void



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!