wilk85
wilk85

Reputation: 65

Ajax call, function callback, javascript

I have function like that

function cryptChange(cr){
        var url = 'https://min-api.cryptocompare.com/data/dayAvg?fsym=' + cr + '&tsym=PLN';
        console.log(url);      // it's just for testing in console

};
cryptChange('LTC');
cryptChange('BTC');

As you can see this code is working fine with URL of AJAX call with JSON data, returning valid URL. Want to make something like that, but in shorter version, I have many lines of code like the ones below and I do want to get less

$.getJSON('https://min-api.cryptocompare.com/data/dayAvg?fsym=BTC&tsym=PLN', function(btc2){
    $('#tt-11').html(btc2.PLN.toFixed(2)); //its passed into html block
});
$.getJSON('https://min-api.cryptocompare.com/data/dayAvg?fsym=BCH&tsym=PLN', function(bch2){
        $('#tt-12').html(bch2.PLN.toFixed(2));
    });

And now I want to mix that cryptChange function with AJAX call to pass parameter for callback and use that in $ ('#tt-11').html (btc2 here <==.PLN.toFixed (2);

Is that clearer guys now?

Upvotes: 0

Views: 77

Answers (1)

Barmar
Barmar

Reputation: 780713

Define a function that takes all the varying parts as parameters.

function getCrypt(from, to, id) {
    $.getJSON('https://min-api.cryptocompare.com/data/dayAvg', {
        fsym: from,
        tsym: to
    }, function(result){
    $('#' + id).html(result[to].toFixed(2));
});

You can then do:

getCrypt('BTC', 'PLN', 'tt-11');
getCrypt('BCH', 'PLN', 'tt-12');

Upvotes: 2

Related Questions