Ad

How To Use For-loop To Do Form Submission In Javascript?

- 1 answer

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?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad