user6224087
user6224087

Reputation:

Currency Layer API

I have got free membership from currency layer. I want to convert currency but its not allowed in free membership. Instead they provided me with a LIVE API where I can get current exchange rates. So I decided to make a way to use this live API for currency conversion by doing some tic tac with the jQuery code. I modified the code to some extent and I think I just nearly succeeded (maybe I am wrong). I have limited working knowledge of jQuery so I got stuck at the last point. Below are the codes with explanation to the issue.

API received from them

// set endpoint and your access key
endpoint = 'live'
access_key = 'YOUR_ACCESS_KEY'; // can't reveal API key

// get the most recent exchange rates via the "live" endpoint:
$.ajax({
    url: 'http://apilayer.net/api/' + endpoint + '?access_key=' + access_key,   
    dataType: 'jsonp',
    success: function(json) {

        // exchange rata data is stored in json.quotes
        alert(json.quotes.USDGBP);

        // source currency is stored in json.source
        alert(json.source);

        // timestamp can be accessed in json.timestamp
        alert(json.timestamp);

    }
});

What I tried

// set endpoint and your access key
endpoint = 'live'
access_key = 'YOUR_ACCESS_KEY';  // can't reveal API key

var from = $('#from').val();
var to = $('#to').val();
var combine = from+to;

// get the most recent exchange rates via the "live" endpoint:
$.ajax({
    url: 'http://apilayer.net/api/' + endpoint + '?access_key=' + access_key,   
    dataType: 'jsonp',
    success: function(json) {
    // exchange rata data is stored in json.quotes
    //var response = json.quotes.combine;
    alert(json.quotes.combine); // HERE IN PLACE OF USDGBP I USED THE COMBINE VARIABLE
    $('#convert').html('response');
}
}); 

combine variable used above is returning undefined. Maybe I did not code properly as I have limited jquery knowledge. If I can fix this then I will be able to use the code most probably. Please help me.

Upvotes: 2

Views: 923

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

To access an object property via a variable holding its name you need to use bracket notation. To set the value of an input, use val(). Try this:

success: function(json) {
  var value = json.quotes[combine];
  $('#convert').val(value);
}

Upvotes: 1

Related Questions