Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax this.id undefined

Tags:

jquery

ajax

I have a list of items I delete using AJAX.

This list is a simple list with divs and each div as an id so when the item is removed from the database I return true and then it removes the line.

Here my code:

HTML

<div id="row1">
<div>item1</div>
<div><a href="...">view</a></div>
<div><a id="1">delete</a></div>
</div>

JS

$('.delete').click(function () {
    if (!confirm('Are you sure you want to delete?')) {
        return false;
    }
    $.ajax({
        type: "POST",
        url: '/delete_record',
        data: 'id=' + this.id,
        cache: false,
        success: function (result) {
            if (result == 'good') {
                $('#row' + this.id).remove();
            }
        }
    });
});

For some reason the this.id does not work because this.id is undefined ... why? I have id="1" on my a href.

like image 735
Derek Avatar asked Nov 18 '11 18:11

Derek


2 Answers

The this you are using refers to the ajax object because there is a new scope within that function. If you want to access variables outwide your scope, you have to declare them before the ajax call.

$('.delete').click(function () {
    if (!confirm('Are you sure you want to delete?')) {
        return false;
    }
    var _this = this;
    $.ajax({
        type: "POST",
        url: '/delete_record',
        data: 'id=' + this.id,
        cache: false,
        success: function (result) {
            if (result == 'good') {
                $('#row' + _this.id).remove();
            }
        }
    });
});
like image 81
Niels Avatar answered Nov 16 '22 03:11

Niels


Your ID should not start with a number. Here is how to formulate a valid id: What are valid values for the id attribute in HTML?

this within your success callback function does not refer to the this in your click handler function. So you need to make a reference to this in your click handler so it can be accessed in your callback function:

$('.delete').click(function () {
    if (!confirm('Are you sure you want to delete?')) {
        return false;
    }
    var that = this;
    $.ajax({
        type: "POST",
        url: '/delete_record',
        data: 'id=' + this.id,
        cache: false,
        success: function (result) {
            if (result == 'good') {
                $('#row' + that.id).remove();
            }
        }
    });
});
like image 35
Jasper Avatar answered Nov 16 '22 04:11

Jasper