Search code examples
jqueryajaxjsonreturn-valuejquery-callback

$.json call jQuery doesn't return a value into a variable


i've got a problem with a $.json jQuery call function, this is my code :

// function to get currency live rates from yahoo api keys

function getRate(from, to) {        
  $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22'+from+to+'%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=', function(data) {

    var rate  = data.query.results.rate.Rate; 

    return rate; 

  });

}// end of function

var receive = getRate('USD','EUR');

Solution

  • Finally i found the solution of return a value into a variable with $.ajax call function, check the code above, works perfect for me, btw thank you all guys :)

    var rate = [ ]; // Step 1 , we create a new array, usefull because we will store here the return value

    // Step 2 , we create our function below

    function getRate(from,to) {

    //Step 3, the ajax call inside a variable

    var ajaxCall = $.ajax({

    async:false,
    dataType:"json",
    type:'GET',
    url:'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22'+from+to+'%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=',
    success: function(data) {
    result = data.query.results.rate.Rate;
    rate.push(result); //we push the result into the array
    

    } });// ajax call end

    if(rate.indexOf()<=0) {

    ajaxCall.abort();
    return calc;

    }

    }//function finish here

    // and then voilà :)

    var returnValue = getRate('USD','EUR');

    // now do whatever you want

    // for example :

    alert(returnValue);