简体   繁体   中英

jquery - 2 ajax calls simultaneously

I want to run 2 AJAX calls simultaneously. I tried the below code but it waits for ajax ({export.php}) to finish and then ajax({display.php}) is run.

I want to run these 2 AJAX calls at the same time. For example, while export.php is running it should also run display.php at same time. How can I do this?

When I click on a button it calls export.php to convert the database table to a CSV file. I also want to show the progress bar ie how many records have finished, 1% , 2% ... 100% . That percentage value is written in the display.php file so to make a progress bar I need to run the 2 AJAX calls simultaneously.

$('.tocsv').on('click', function() {
  var display = setInterval(function() {
    $.ajax({
      url: 'display.php',
      method: 'get',
      success: function(data) {
        console.log(data);
      }
    });
  }, 500);

  $.ajax({
    url: 'export.php',
    method: 'post',
    success: function() {
      clearInterval(display);
    }
  });
});

Edit The problem was in display.php file i had written session_start() . I just deleted that line and changed ajax code to this

                url: 'display.php?file=<?=session_id()?>',
                success: function (data) {
                    $('#res').html(data);
                }
            });

but why it doesn't work when i write session_start()?

In AJAX the first alphabet A is for "Asynchronous". So calling asyn way is not the issue here. The problem is with making ajax request inside the setInterval. I am very sure that you server is not responding in the time delay you have given ie 500ms and you are flooding your server with multiple request every half second. By the time one request is completed you have made at least 4 or 5 request to your server which is the root cause of you issue. Remove setInterval and if you want you call to be made after 0.5 sec use setTimeout.

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