Reputation: 2553
I have written a javascript in the console of chrome to download many files from a web. The javascript is as follows:
for (i=0; i<100; i++) {
$("input[name=id]").val(i);
$("form").submit()
}
I expected I can download all the files whose id is from 0 to 99; however, what I am able to download is only the last file (i.e. file with id =99). Why does this happen?
Upvotes: 1
Views: 3399
Reputation: 4980
I think you are missing the responses. When you call first form, the browser start the connection, but just after that, you ask for the second form. Whitch cancel the first.
You need to call that forms with AJAX
, to store each request with the correspondent response in some variable.
Your problem is like when you click too many links in a page before let it load the first link. Finally the loaded link is the last clicked.
TRY THIS SOLUTION:
You need to que keep some time between calls to handle response and start the download, so wright a function like this:
function submitFormAndWait(i) {
//this is your code to submit
$("input[name=id]:hidden").val(i);
$("form").submit()
//wait some time and call next form
if (i < 100) {
setTimeout(function(){ submitFormAndWait(i + 1); }, 3000);
}
}
POSSIBLE PROBLEM:
When you submit a form in the browser, this will load the response as the current page, and the script will start from zero other time.
Upvotes: 1
Reputation: 1035
The best way to do that is using AJAX and FormData.
Assuming you're using jQuery in your site, some pseudocode for this:
var url = '/some/ajax/url';
var i = 0;
for ( ; i < 100; ++i) {
var formData = new FormData();
formData.append('some-number-field', i);
// Send data using Ajax POST
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function(response) {
// Do something on success
},
error: function(xhr, status errorThrown) {
// Do something on error
}
});
}
Upvotes: 1