simultaneous ajax requests angularjs?

All we need is an easy explanation of the problem, so here it is.

i want to send multipal ajax request at a time. this is my js code.

<a class='btn btn-success' ng-click='getDataajax()'>Re Check</a>

app.controller('customersCrtl', function($scope, $http, $timeout) {
    function wrapper() {
        $scope.getEventSeconds();
        $timeout(wrapper, 5000);
    }
    $http.get('cget.php', {
        params: {
            'action': 'get_info'
        }
    }).success(function(data) {
        $scope.list = data;
        $scope.currentPage = 1; //current page
        $scope.entryLimit = 10; //max no of items to display in a page
        $scope.filteredItems = $scope.list.length; //Initially for no filter  
        $scope.totalItems = $scope.list.length;
    });
    $timeout(wrapper, 5000);
    $scope.getDataajax = function() {
        $http.get('cget.php', {
            params: {
                'action': 'set_info'
            }
        }).success(function(data) {});
    };
    $scope.getEventSeconds = function() {
        $http.get('cget.php', {
            params: {
                'action': 'get_info'
            }
        }).success(function(data) {
            $scope.list = data;
            $scope.currentPage = 1; //current page
            $scope.entryLimit = 10; //max no of items to display in a page
            $scope.filteredItems = $scope.list.length; //Initially for no filter  
            $scope.totalItems = $scope.list.length;
        });
    };
})

This is working find get_info ajax is send in every 5 second. but when i fire set_info ajax and then the get_info ajax is fire it’s waiting for finish set_info ajax.

i want to working both link at a time when get_info fire then is not waiting untill the set_info ajax is finished.

Thank you.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I think what you’re interested in is $q.all. From the documentation:


all(promises);

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
Parameters

Param    | Type                             | Details
promises | Array.<Promise> Object.<Promise> | //An array or hash of promises

Returns a single Promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.


Example

$q.all({
  users: $http.get('https://api.github.com/users'),
  repos: $http.get('https://api.github.com/repositories')
}).then(function(results) {
  var users = results.users.data;
  var repos = results.repos.data;
});

Here’s a plunker of this in action.

Update

After rereading the issue a few more times, I realized that making two ajax requests asynchronously while wanting to only have a single callback for both was not the issue of the original question.

From my understanding, the question is asking how to have multiple ajax requests happen simultaneously, with no regards to which happens first, and no need for a common resolved promise callback (as my original answer addresses).

When an ajax request is made (e.g. $http.get(...);), execution of javascript won’t stop. If another ajax request is made, it will fire regardless of whether or not the first one finished or not. Having an ajax request continually occurring in an interval loop and having a button event fire an independent ajax request shouldn’t cause any conflict.

Although the code in the question isn’t ideal, I can’t exactly see why the ‘get_info’ request is waiting for the ‘set_info’ request to complete. I’ve created a jsFiddle to try and recreate the original code’s functionality and it seems to be working as expected:

http://jsfiddle.net/Tnt56/

I used jsFiddle since it has an /echo/json/ api feature to test ajax functionality. If you open your developer tools to the console, this fiddle will log key points of the ajax requests. The $timeout wrapper fires every 5 seconds and I’ve set the GetDataajax’s response to be delayed by 6 seconds. When the getEventSeconds function gets logged in the console, click the GetDataajax button. It will log that it started, then the getEventSeconds will log again, and finally the GetDataajax will get resolved.

On a side note, I had to use jQuery’s $.ajax() instead of Angular’s $http because for some reason, the $http posting wasn’t playing nice with jsFiddle’s echo service, despite playing with the request headers (Content-Type). The request ‘works’ but the delay feature wouldn’t.

Method 2

I rewrote your controller to use closures in order to make every call asynchronous and keep it DRY.

I tested this and it works, check it out here: http://jsfiddle.net/s6uFx/2/

app.controller('customersCtrl', function ($scope, $http, $timeout) {
  function cget(action) {
    return $http.get('cget.php', {params: {action: action}});
  }

  $scope.getDataajax = function () {
    cget('set_info')
    .success(function (res) {
        console.log(JSON.stringify(res));
    });
  };

  $scope.getEventSeconds = function () {
    cget('get_info')
    .success(function (res) {
      console.log(JSON.stringify(res));
      $scope.list = res;
      $scope.currentPage = 1; //current page
      $scope.entryLimit = 10; //max no of items to display in a page
      $scope.filteredItems = $scope.list.length; //Initially for no filter
      $scope.totalItems = $scope.list.length;
    })
    .then(function () {
      // and start to loop
      $timeout($scope.getEventSeconds, 5000);
    });
  };

  // this call replaces the first $http.get and starts the loop
  $scope.getEventSeconds();
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply