0

I have to make numerous AJAX calls and want to set up a simple method to handle this. I created the following

function testingAjax(url) {
  $.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    url: url,
    data: "{}",
    dataType: "json",
    success: function(data) {
      //alert(data);
      return data;
    },
    error: function(err) {
      alert('error')
    }
  });
};

When I call testingAjax from another method, I get an Undefined error, yet when I alert from within testingAjax it is correct.

function testingCall(){
    var data = testingAjax(url);
    alert(data);
}

Basically, I want to return the data from the AJAX call, and parse it elsewhere. What am I doing wrong?

Seth
  • 10,198
  • 10
  • 45
  • 68
SteveV
  • 429
  • 3
  • 8
  • 18
  • This general question has been asked hundreds of times (it is a common point of learning). The Ajax call is asynchronous. Your function returns long before the ajax call is done. As such, you cannot return the value directly. You must use promises or callbacks. See the question yours has been marked a dup of for many possible solutions. – jfriend00 Feb 02 '16 at 21:28
  • Thanks! Wasn't sure what to even search on and figured someone would post some hints at what to do. – SteveV Feb 02 '16 at 22:52

1 Answers1

2

You'll want to add a callback param (which is a function) and pass it to success in place of what you already have.

function testingAjax(url, cb) {
  $.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    url: url,
    data: "{}",
    dataType: "json",
    success: cb,    
    error: function(err) {
      alert('error')
    }
  });
};

To use it:

testingAjax('myurl', function(data) {
  console.log(data);
});

This will take the value of the success callback and immediately pass it as an argument to your custom callback, which will allow you access to data.

Seth
  • 10,198
  • 10
  • 45
  • 68