What's the optimal way of making these AJAX GET requests with jQuery & JSON API?

I'm outputting API data on separate pages coming from different end point urls, ie. https://api.server.com/first, https://api.server.com/second, etc.

The code is working, but it seems awfully redundant and I'm sure there's a better way of expressing this that's more optimal and faster:

var $rubys = $('#rubys');

$(function () {
   $('#loading-rubys').show();
   $.ajax({
       type: 'GET',
       url: 'https://api.server.com/first/',
       success: function(rubys) {
           $.each(rubys, function(i, ruby) {

$rubys.append('$'+parseFloat(ruby.price).toFixed(2)+' | 
$'+parseFloat(ruby.attribute).toFixed(0));
           });
       },
       complete: function(){
       $('#loading-rubys').hide();
       }
   })
});    

var $emeralds = $('#emeralds');

$(function () {
   $('#loading-emeralds').show();
   $.ajax({
       type: 'GET',
       url: 'https://api.server.com/second/',
       success: function(emeralds) {
           $.each(emeralds, function(i, emerald) {

$emeralds.append('$'+parseFloat(emerald.price).toFixed(2)+' | 
$'+parseFloat(emerald.attribute).toFixed(0));
           });
       },
       complete: function(){
       $('#loading-emeralds').hide();
       }
   })
});   

The following:

var $rubys = $('#rubys');
$('#loading-rubys').show();

are set for each post page using YAML front-matter (Jekyll) like so:

---
title: Post about Ruby
var-id: rubys
load-id: loading-rubys
---

and output them in HTML:

 <div id="{{ page.var-id }}">   
 <div id="{{ page.load-id }}">
     <img src="/assets/img/loading.svg"/>
 </div>
 </div>

Current workflow

So basically whenever I create a new post, I:

  • Set the var-id and load-id custom parameters for each post in the front-matter

  • Create a new function to include those and make a new GET request to the respective url, ie. https://api.server.com/third/, https://api.server.com/fourth/.

How would you write this better?

1 answer

  • answered 2018-01-13 17:26 Peter Darmis

    Something like this could help.

    function getGems(gems,gemsURL) {
    var $gems = $('#'+gems);
    $('#loading-'+gems).show();
       $.ajax({
           type: 'GET',
           url: gemsURL,
           success: function(data) {
               $.each(data, function(i, v) {
                   $gems.append('$'+parseFloat(v.price).toFixed(2)+' | 
                   $'+parseFloat(v.attribute).toFixed(0));
               });
           },
           complete: function(){
           $('#loading-'+gems).hide();
           }
       });
    }
    $(function () {
        getGems('rubys','https://api.server.com/first/');
        getGems('emeralds','https://api.server.com/second/')
    });