Reputation: 17184
i have list of rows that user select and i want to delete them, one by one and show the result in the end.
obviously if i just do simple loop and call each time ajax function, but how can i loop and check which one successed and which one failed and when they are all done?
how would you do it? what is proper way of doing the bulk editing/deleting?
Upvotes: 0
Views: 3507
Reputation: 103417
Each ajax request is going to have overhead associated with it. It would be a bad idea to make a call for each row because it could overload the server with requests and you could DoS yourself if your receive enough traffic. Also, all browsers have a limit on how many HTTP requests can be made at once, so (depending on the browser), the deletions will happen in bursts, not all at once, even if you tell them to execute one after another.
Your best option would be to group the rows to edit/delete into a JSON array and send them to the server in a single request. On the server you can then parse the JSON and delete the items accordingly. Once you're finished, return a JSON array containing your results.
This jQuery pseudo-code code assumes you're either targeting browsers with a native JSON object, or you're using json2.js. Basically, this code just looks for "the hidden ID" field in each row of the table you display to the user and adds it to an array. You can adjust this as you feel it is needed.
var recordsToDelete = [];
$("tr.myRow").each(function() {
var id = $(this).find("input:hidden").val();
recordsToDelete.push(id);
});
var json = JSON.stringify(recordsToDelete);
Dealing with results can be harder. You should design your system so that (if successful), every row is deleted. Unless you're dealing with a very complex system, you should never have a situation where some rows pass and some rows fail. If this happens you need to re-consider your system architecture. jQuery has events for success
and failure
which you can use to deal with the general success or failure of the request, which I recommend you use.
Continuing from the code above, this is one way to deal with deleting records. I use the complete
event here for simplicity's sake, but you should use the success
and failure
events if possible. The complete
event always happens, whether a request succeeds or fails.
$.ajax({
url: "http://stackoverflow.com/questions/1653127",
type: "POST", // Always use POST when deleting data
data: { ids: json },
complete: function(xhr, status) {
var response = JSON.parse(xhr.responseXML);
// Response will be an array of key/value
// pairs indicating which rows succeeded or failed
for (var i = 0; i < response.length; i++) {
var recordID = response[i].recordID;
var status = response[i].status;
// Do stuff with the status codes here
}
}
});
In Response to Comments:
Upvotes: 9