简体   繁体   中英

JQuery call not working after Ajax call succeeds

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM