i have displayed data using ajax
$.ajax({
url: "ajs/index",
type: "GET",
dataType: "JSON",
success: function(data) {
var output="";
for(i=0;i<data.length;i++)
{
output+="name:"+data[i].name
+"<input type='button' class='delete' value='Delete' data-id=" + data[i].id + "><br>"
}
$("#result").html(output);
} //success function closed
}); //ajax call closed
// when delete button is clicked.
$(document).on("click", ".delete", function(){
var id = $(this).data('id');
$.ajax({
url: "ajs/"+id,
type: "delete",
//data: "22",
//dataType: "html",
success:function(data) {
alert("success")
},
error: function(){
alert("error")
}
}); // delete ajax() closed
return false;
});//delete click() closed
I have set of records displayed with each record having a delete button. When I click on that button the above function should be called. When I see my console it is triggering twice. First it is displaying deleting ajs/idno.
and then it is showing ajs/idno. 404 not found
error.
And the worst thing is even after deleting the record it is showing error message. It is not showing success message.
Looks like you are setting the click
event each time the ajs/index
is called.
You should put the click
event outside of this ajax and write it like :
$(document).on("click", ".delete", function(){
var id = $(this).data('id');
$.ajax({
url: "ajs/" + id,
type: "delete",
success: function(data) {
alert("success")
},
error: function() {
}
}); // delete ajax() closed
return false;
}); //delete click() closed
If the element with the .delete
class is created dynamically, it'll work.
You can
$(".delete").unbind("click");
before attach event to $(".delete").