Amit Kumar
Amit Kumar

Reputation: 905

Design : One AJAX Call or multiple AJAX calls to get list of details

I have a use case where i want to fetch card details, I have 2 REST APIs

/user/{id}/getCards // gives list of cards for that user

In Back-end this is how it works, i make a call to one service which gives me list of cardIds, then i make another call to fetch card details for each cardId and return a list of cardDetails in json response.

/user/{id}/getCard/{cardId} // gives one card's detail with cardId for that user

In Back-end this is how it works, i make a call to second service passing cardId and json response contains only details of one card.

Given that i have CardIds already with me on page load, What is the best approach to follow.

Approach 1: Make only one call and get all cards and show in UI at once. It will cause me 2 calls in backend.

Approach 2: Iterate in javascript and make multiple AJAX calls one bye one (can be done async) and fetch one by one card details and show in UI. What if any call fails.

Upvotes: 1

Views: 369

Answers (2)

Haresh Gopal
Haresh Gopal

Reputation: 1

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

<input type="text">

<input type="text">

<input type="button" onclick="fetchprofiledetails()">

<input list="browsers" id="datadyna">
<datalist id="browsers">

</datalist>

<script>
function fetchprofiledetails(){
$.ajax({
 url:'data.json',
 success:function(response){
  var x= {};
  x=response;
    alert(x.widget);
 }
})
} 
$(document).ready(function(){
  var x= {};
$('#datadyna').on('keyup',function(){
 if($('#datadyna').val().length >= 4){
    $.ajax({
     url:'data.json',
     success:function(response){

 x = JSON.parse(response);
 var option ='';

  $.each(x.widget.window, function(i, field){
            //$("div").append(field + " ");
            option = option + '<option value='+  field+'>'
        });

    //option = option + '<option value='+ x.widget.window[i] +'>'

 $('#browsers').append(option);
    //alert(x.widget.window.title);
 }
})
 }
});
});


</script>

Upvotes: 0

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29993

I think /user/{id}/getCards should just allow an array of filters to be passed to it and return an array of objects matching filters. It is a standard approach and is perfectly ok in REST.

There is no need to make separate requests since this is really slow for the client and can cause excessive load to the server. I do not see the need to fetch entities one by one so inaffectively.

Upvotes: 1

Related Questions