0

I'd like to be able to have a js function that contains an ajax call to return a value that the ajax success handler returns.

Here's my jsfiddle of where I'm at right now. I'm using a dummy json endpoint for illustration. I want someFunction to return the same thing I'm currently logging in the console.

http://jsfiddle.net/ivansifrim/qgfo6zqe/

$(document).ready(function(){
  function someFunction(){
    $.ajax({ 
      url: 'http://api.openweathermap.org/data/2.5/weather?id=2172797',
      type: 'GET',
      success: function(result) {
        console.log(result.coord);
        $("#result").html(result.coord.lat);
      },
      error: function(result) {
        console.log("something went wrong");  
      }
    });
  };

  $("#click-test").click(function(){
    someFunction();
  });
});

I would really appreciate some help and am more than happy to provide any more context if needed. Thank you!

user1683056
  • 139
  • 8
  • Not possible, unless you use a synchronous AJAX (which is kind of an oxymoron, and is heavily suggested against, but possible). You can never ever return results from asynchronous functions. Figure out what you want to do with the result after it has been received, and do it (or call for a function to do it) from inside the success handler. See more details in the linked question. – Amadan May 25 '15 at 01:52
  • Thank you - I really appreciate you taking the time to respond. Take care and keep helping people! – user1683056 May 25 '15 at 03:55

0 Answers0