0

I have an Ajax call that looks like this:

$("#start-upload-btn").click(function(){
    $.ajax({
        type: "post",
        url: "",
        data: {
            newProjectName: $('#project-name').val(),
            csrfmiddlewaretoken: csrfToken
        },
        success: function(data){
            $("#file-upload").click();
        }
    })
});

Upon success I want to perform a click on the element with id #file-upload to launch the file selection dialogue, but putting the code in success function fails to work. It works anywhere else. Is there something special about the scope of the Ajax success function? I really cannot figure this out.

Thanks

Francis N
  • 137
  • 1
  • 11

1 Answers1

1

There is nothing inherently problematic about issuing a click on any normal element (including a button) from an ajax success callback.

The problem is that a file-input dialog is not a "normal element". It has some specific security limitations - one of which clearly limits your interaction with it.

This is demonstrated by the following fiddle: https://jsfiddle.net/qhfwobpz/

You'll see that issuing a click on the file-upload directly works without a problem. Doing it from an ajax callback yo'll see the callback is called, but the file dialog never shows.

This answer gives more detail as to the "why" and it boils down to you can open the dialog from an event issued by the user but not purely programatically.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • thanks so much for your time and effort in the response. That thread made a lot of sense. I was trying to automate the spawning of the file input box after user successfully creates a project. But I think on success of project I will have to enable an upload button instead which will have to be clicked afterwards to show the file input box. Thanks again!! – Francis N Jul 04 '17 at 16:35