1

Just curious about ajax calls, so I have multiple ajax call function which calls different Url endpoints but I find it sometimes one call fails and others get success.

Say I have these function and I know both calls works when I console log them, it returns me the value I needed however these calls will trigger once the page has loaded.

function xs () {
 $.ajax({
    url: 'api/endpoint1?loc="space"',
    method: 'GET'
    ...
 })
}
function xd () {
 $.ajax({
    url: 'api/endpoint2?name="x"',
    method: 'GET'
    ...
 })
}

How I trigger these functions and I call this file say calls.js in my html and this will fire the ajax calls. But sometimes only 1 of them will get a success or sometimes both.

function init() {
 xs();
 xd();
}
init();

So just wondering if there's a better way of handling multiple AJAX calls specially if you have more than 2.

MrNew
  • 1,384
  • 4
  • 21
  • 43
  • This question isn't clear. What exactly are you missing? – Liam Dec 16 '16 at 12:54
  • @Liam Sorry that was a typo, well I just find it weird that some of my ajax calls fails and the others get successfully called. Say `function xs()` fails in the first load then it will get success in the 2nd but `function xd()` will fail. – MrNew Dec 16 '16 at 12:56
  • You can insert xd() inside a xs() success/fail. Best practice is to do a single ajax call and doing on back-end the other business logic (if one fail call other etc..) – Milaci Dec 16 '16 at 13:01
  • http://jsfiddle.net/EN8nc/164/ – Ravi Roshan Dec 16 '16 at 13:04
  • 1
    I would recommend looking at promises - https://api.jquery.com/promise/ – phooey Dec 16 '16 at 13:05
  • you wait for callback for all ajax request i hope this link helps you. => https://css-tricks.com/multiple-simultaneous-ajax-requests-one-callback-jquery/ – Lalji Dhameliya Dec 16 '16 at 13:09
  • so you only want `xd()` to be called if `xs()` is successful? – Liam Dec 16 '16 at 13:17
  • 1
    No, I don't need to rely whether one is successful as in theory calling them individually like mine would give me success on both. But for some weird reason it doesn't – MrNew Dec 16 '16 at 13:19
  • What? This question makes no sense. If ones failing then it's the server side code where the issue lies not the javascript – Liam Dec 16 '16 at 13:22

6 Answers6

3

If you're looking to have the second request execute regardless of the outcome of the first (success or fail), call it via jqXHR's done:

function xs() {
 $.ajax({
    url: 'api/endpoint1?loc="space"',
    method: 'GET'
    ...
 }).done(function(){
     $.ajax({
         url: 'api/endpoint2?name="x"',
         method: 'GET'
         ...
     });
   });
});

Otherwise, look into promises using Promise.all():

You can read more into promises here

init(){

    Promise.all( [
       $.ajax({
          url: 'api/endpoint1?loc="space"',
          method: 'GET'
          ...
       }),
       $.ajax({
           url: 'api/endpoint2?name="x"',
           method: 'GET'
           ...
       })
    ]).then(function(){
       //Some other code - Won't run until both requests have finished
    });     
}
Fueled By Coffee
  • 2,467
  • 7
  • 29
  • 43
  • Well my idea is to call them all at once without relying on the first function to success. In theory they all should get success calls because they're being called individually. – MrNew Dec 16 '16 at 13:17
  • I edited to look into promises. Does that help get you any closer? – Fueled By Coffee Dec 16 '16 at 13:48
0
var i = 0;
function xs () {
$.ajax({
url: 'api/endpoint1?loc="space"',
method: 'GET',
success: function(data){
 if(i == 0){
   i++;
   xd();
 }

}
});
}

function xd () {
$.ajax({
url: 'api/endpoint2?name="x"',
method: 'GET',
success: function(data){
 if(i == 0){
   i++;
   xs();
 }
}
});
}
Parag Yelonde
  • 34
  • 1
  • 12
0
function xs () {
    $.ajax({
        url: 'api/endpoint1?loc="space"',
        method: 'GET'
        ...
        success: function() {
            $.ajax({
               url: 'api/endpoint2?name="x"',
               method: 'GET'
               ...
            })
        }
    })
}

function init() {
 xs();
}
init();
Shaybi
  • 318
  • 2
  • 9
0

You can see if it's a problem in your frontend or in the backend with the inspector of Chrome. In the Network tab filter by XHR. if you don't see both calls there it's a front end problem if not it's probably a problem with the response.

In other hands you can control when launch the calls. For example:

using the document ready:

$(function(){ 
 //jQuery code here 
})

or using promises you can execute both and wait until you receive the data using promise.all()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

haran
  • 101
  • 1
  • 7
0

Using RxJS, you will be able to achieve what you describe, which is, if I understand correctly, launch several asynchronous calls in parallel, and then perform an action when all calls complete.

There's a (rather poorly documented last time I checked) feature called forkJoin just for that. Here's a sample (written in TypeScript but you get the idea) :

  /**
   * Get some Lists of Values.
   */
  public getLovs(codes: string[], lang: string) {
    return Observable.forkJoin(
        codes.map(code => { return this.getLov(code, lang); })
    );
  }

In this code, getLov returns an Observable (which is some kind of evolved Promise). The getLovs function itself returns an Observable when all async calls have been performed. The resulting Observable is an array comprised of the result each individual async call. Very useful.

Blablalux
  • 485
  • 1
  • 5
  • 9
  • He hasn't asked for an RxJs solution. there is no need to include this library to solve this problem and doing so would be massive overkill – Liam Dec 16 '16 at 13:21
  • OK so you downvote a solution that works but you don't downvote a solution that loops forever like the one above. Besides, as far as I can tell, no single answer in this thread except mine allows to launch multiple async calls in parallel as the OP seemed to request. – Blablalux Dec 16 '16 at 13:28
  • Actually I've downvoted both.... – Liam Dec 16 '16 at 13:28
  • **if** thats what the OP wants (which isn't clear but well..) It's perfectly possible to achive this without the addition of a library – Liam Dec 16 '16 at 13:29
  • I wasn't asking you to downvote the other either. Of course the OP hasn't asked for an RxJs solution specifically, he asked for a solution that works according to his request. – Blablalux Dec 16 '16 at 13:31
-1

Put your Second ajax call inside the success/complete function of the first and it will execute for sure

Anoop Reghuvaran
  • 329
  • 2
  • 10
  • 1
    but that will do a chain call which isn't the idea of the function above, otherwise I'd have done that. I want them to execute all at once. Plus this should be a comment than an answer. – MrNew Dec 16 '16 at 12:59