1

Here is a function which does an ajax call

function gettrans(callback) {
  var xml = $.ajax({
    method: 'GET',
    url: 'url/?callback=jsonpCallback',
    dataType: 'jsonp',
    jsonp: !1,
    jsonpCallback: "jsonpCallback",
    data: { drop_lang: dropjslang,},
    success: function (data) {
      callback();
    },
    error: function (data) {
    }
  });
  return xml.responseJSON
}

I want to return xml.responseJSON but I get undefined.

What may be a solution?

GG.
  • 21,083
  • 14
  • 84
  • 130
Chris Roberts
  • 99
  • 1
  • 6
  • You can't return a value synchronously if the value itself is fetched/produced asynchronously. `$.ajax` call is asynchronous so `gettrans` cannot return a value synchronously. You can return a promise. Or you can make the ajax call upfornt and have the success call back set the value/data which you can return using gettrans, Welcome to asynchronous programming ! – bhantol Dec 14 '16 at 04:57

2 Answers2

2

Pass the result to your callback:

function gettrans(callback) {
  $.ajax({
    ...
    success: function (data) {
      callback(data);
    },
    ...
  });
}
GG.
  • 21,083
  • 14
  • 84
  • 130
1

You're supposed to pass a callback function in success:

success: function(response) {
    console.log(response); // response is the data returned by your ajax query
}
Oscar
  • 805
  • 2
  • 10
  • 24