Reputation: 867
var items=[];
items.push(data);
I am using an array to store my data, and then submit using ajax. For the first time submission, it works fine. But when submit subsequently, it will submit null value together with data passing to server.
I am using the method below to clear the array, but i found that the previous data just set to null. For example, for the first time i passed value 1, successful. For the second submission, i clear the array and store new value, e.g. i pushed value 2 to the items[], when submit it will submit null and 2.
items.splice(0);
How can i fix it? I need to reset the array every time submit the value.
Code:
var items=[];
$("#selection").click(function(e) {
$(":checkbox").each(function() {
if(this.checked === false) {
this.checked = true;
items.push(this.id);
}
});
});
$('#grid').submit(function(e){
e.preventDefault();
var formdata = {
data:items
};
$.ajax({
type: "POST",
url: "/add",
data: formdata ,
dataType:'html',
success: function(data) {
alert("added");
}
});
});
Upvotes: 0
Views: 4698
Reputation: 32354
You simply set the array to a empty array after the ajax
success: function(data) {
alert("added");
items=[];
}
or better empty it at each click
$("#selection").click(function(e) {
items=[];
// rest of the code
Upvotes: 2
Reputation: 1652
If you want to reset all array till leave it empty you can do this :
var array = [1,2,3,4,5,6];
array.length = 0;
it that way you can reset your array
when you use :
array.splice(0) // this will delete items from index that you passed, only if you passed the first parameters
Hope it helps you.
Thank you for the note @nnnnnn
Upvotes: 0