I have a form with some data and upload. The upload could be initiated only if data were successfully received and processed. To do that, I make an ajax call where I
The last thing with click() doesn't work as it seems that asynchronous call blocks opening an upload window. It works only if I set async: false
.
I cannot find anything in documentation and this site and want to know what is the problem there and how to make it working keeping the call asynchronous?
Example:
$.ajax({ type: "POST", url: "/Save", data: jsonText, dataType: "json", //async: false [1] }).done(function (msg) { $("#upload").click(); }); //$("#upload").click(); [2]
Demo: http://jsfiddle.net/c2v00uxn/
Note:
UPDATE
It's not about how to make a "click" in general, it's about how to click after an asynchronous ajax call (as of now, works only with non-asynchronous call).
Its not possible right now to open a file popup window from an async ajax callback due to w3c recommended security features in the browsers.
In the file input element's activation behavior it first checks if the algorithm is allowed to show a popup, if not then abort the next steps without doing anything else. from w3c.org
An algorithm is allowed to show a popup if any of the following conditions is true:
DocumentEvent.createEvent("Event")
method, modified using the Event.initEvent()
method, or dispatched via the EventTarget.dispatchEvent()
method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false. otherwise. http://www.w3.org/TR/2012/WD-DOM-Level-3-Events-20120614/#trusted-events.)The task in which the algorithm is running is currently running the event listener for a trusted event whose type is in the following list:
w3c.org
In your code the click event is not triggered by the user but its triggered by the ajax complete callback. Here the browser declares that the event cannot be trusted to open a popup. In some browsers you can see an isTrusted
attribute set to true if the event is declared as trusted.https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
Note
Different browsers trap the difference between a script activated cick and a real user using different methods.
What you can do in this scenario is to disable the file input button(or the entire form) and enable after ajax is done. That way the user wont click on the upload button until the ajax request gets completed. As of now there is no other way to do both in one click since there is a timeframe limit also for opening popup. When I checked in chrome the timeframe is 1000ms. 1000ms after the user action, window will not get opened.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With