0

I have this method:

    var chineseCurrency = getChinese();
    function getChinese(){
        return $.ajax({
            context: this,
            type: 'GET',
            dataType: 'json',
            url: "https://www.cryptonator.com/api/ticker/usd-cny"
        });
    }

That is what printed when console.log(chineseCurrency);:

enter image description here

I am not able to make chineseCurrency equal to "price", so it would be "6.80071377". How can I do that? Tried chineseCurrency.responseText, nope, chineseCurrency['responseText'], nope. Tried to JSON.parse(chineseCurrency), nope. Nothing works!

Sorry if repeated, couldn't find any answer at Stackoverflow.

AmazingDayToday
  • 3,724
  • 14
  • 35
  • 67

2 Answers2

1

How do I return the response from an asynchronous call?

Data that is received as response to asynchronous ajax call cannot be returned from the function that calls $.ajax. What you are returning is XMLHttpRequest object (see http://api.jquery.com/jquery.ajax/) that is far from the desired data.

var chineseCurrency = null;
function getChinese(){
    return $.ajax({
        context: this,
        type: 'GET',
        dataType: 'json',
        url: "https://www.cryptonator.com/api/ticker/usd-cny",
        success: function(data) {
            alert("success1: chineseCurrency=" + chineseCurrency); 
            chineseCurrency = data.ticker.price;
            alert("success2: chineseCurrency=" + chineseCurrency);
            // do what you need with chineseCurrency 
        }
    });
}
Community
  • 1
  • 1
Igor
  • 15,833
  • 1
  • 27
  • 32
  • все равно не работает. – AmazingDayToday Feb 12 '16 at 17:11
  • @SeattleSam Что не работает? Покажите исправленый код, который не работает. Вы используете переменную `chineseCurrency` сразу после вызова `getChinese`? – Igor Feb 12 '16 at 17:15
  • Если я делаю именно так, то вне функции, `chineseCurrency` не виден. Вы знаете, дело в том, что эта функция, в свою очередь, находится в функции, которая использует `callback`. Может быть в этом дело? – AmazingDayToday Feb 12 '16 at 18:26
  • Хорошо, а как манипулировать объект, который я указал в вопросе? Как я могу взять нужные мне данные? – AmazingDayToday Feb 12 '16 at 18:35
  • @SeattleSam Вы не должны "манипулировать" `XMLHttpRequest`. Важно понять, что до выполнения обработчика `success`, `chineseCurrency` нельзя использовать. Я, собственно, хотел это подчеркнуть перенесением объявления этой переменной внутрь `success: function(data) { ... }`. Если она нужна Вам снаружи - посмотрите на исправленный код. Важно не рассчитывать на то, что в этой переменной окажется значение до вызова `success`. А вызывается `success` не Вашим кодом, а `jQuery.ajax`ом. – Igor Feb 12 '16 at 18:59
  • null так и остается. Даже не знаю как мне extract нужный price. Спасибо Вам! – AmazingDayToday Feb 12 '16 at 19:05
  • @SeattleSam - Может, Вы добавите в Ваш вопрос код, который вызывает `getChinese` и использует `chineseCurrency` (с учетом последних исправлений), пока мне не надоело об этом просить :) ? – Igor Feb 12 '16 at 19:08
  • Игорь, все норм. Я разобрался. Спасибо! – AmazingDayToday Feb 12 '16 at 19:51
0

You are not taking the data from that is returned from the Ajax call. instead you are just returning the ajax object.

Change your code to :

    $.ajax(
    {
        context: this,
        type: 'GET',
        dataType: 'json',
        url: "https://www.cryptonator.com/api/ticker/usd-cny"
        data    :{},
        error   : function(data)
        {
            console.log('error occured when trying to find the from city');
        },
        success : function(data) 
        {
           console.log(data); //This is what you should return from the function. 
        }
   });
Jilson Thomas
  • 7,165
  • 27
  • 31