1

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?

1
  • 2
    Can you provide a link to this website, or at least the HTML of the form? Commented Jan 12, 2016 at 2:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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
        }
    });
}

1 Comment

As the form is quite complicated and I am not familiar with java script, how can I do form submission using your code above if I have an existing form which can be accessed by $("form") and wants to change the id variable of the form like this: $("input[name=id]:hidden").val(i);?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.