The question in OP was discussed on SO many and many times. The name of the problem is Asynchronous function execution in the loop.
First look what is wrong with OP:
var smth = new Array("1","2","3");
for(var i=0;i<smth.length;i++){
$("#id"+i+"_del").click(function(){// i comes from the loop and is OK
$.ajax({
type: 'POST',
url: 'delete.php',
data: {filek : smth[i]},//the code runs *after* the loop is completed and **i** is 3 (in this case)
success: function(html){
console.log(html);
}
});
});
};
How to fix it?
If ES6 is available then there is no problem. Read documentation
for(let i=0;i<smth.length;i++){// i is scoped to the loop
// ^^^
// OP code
}
Else a closure is the solution
var smth = new Array("1","2","3");
for(var i=0;i<smth.length;i++){
(function(j){ // it is possible to use **i** but it will be different **i**
$("#id"+j+"_del").click(function(){//
$.ajax({
type: 'POST',
url: 'delete.php',
data: {filek : smth[j]},// j keeps the value
success: function(html){
console.log(html);
}
});
});})(i);
};