Reputation: 1088
I have a little question. say i have a js function
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
$("#div_"+id).html(html);
} });
window.open('File_download.php?file_id='+id, '_blank' );
});
as you can see window.open
call is after $.ajax call
Does it guaratee that $.ajax call will get executed every time before the page reloads and if no then
shouldn't we declare window.open
in success function?
In my opinion when there is slow response from server the page will reload first and it may happen that $.ajax
call will be interrupted by window.open
function
but i get a downvote for the same reason here stackoverflow.com/questions/12908138/how-to-get-the-id-or-name-of-related-file/
And Thanks for making my belief stronger
Upvotes: 0
Views: 208
Reputation: 789
In your example, the window.open
function will always (!) be called before the success
callback function given to the ajax
call. Ajax traffic is always asynchronous, whereas the window.open
function resides in the synchronous JS <script>
tag.
Since JavaScript is single-threaded, all synchronous statements will always be executed before any asynchronous functionality like ajax setTimeout animate
etc.
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html) { // asynchronous functionality
$("#div_"+id).html(html);
}
});
// within synchronous script statements
window.open('File_download.php', '_blank' );
Upvotes: 1
Reputation: 665090
Yes, Ajax is asynchronous so you will open that window right after you started the XHR process. To download the processed data, open the new window from the success callback. Yet I'm not sure what you mean by "before the page reloads" - there is no code which does that.
Also I don't know how your server behaves, the file_download.php
seems to be independent from your ajax call. Shouldn't you pass the download_number
you received via ajax in there?
Upvotes: 1