0

I'm trying to return data from a callback function, but it doesn't work... Instead it just returns "undefined".

Code(JS):

var apiUrl = "/dev/mysqlApi/api.php";
function api(actionType, newArray)
{
    if(typeof newArray == "undefined")
    {
        $.ajax({ url: apiUrl, type: "POST", data: { actionType: actionType }, success: function(data){ returnData(data); } });
    }
    else
    {
        $.ajax({ url: apiUrl, type: "POST", data: { actionType: actionType, newArray: newArray }, success: function(data){ returnData(data); } });
    }
    function returnData(data)
    {
        return data;
    }
    return returnData();
}
Jojo01
  • 1,269
  • 4
  • 14
  • 35
  • Where do you call `api` function?? – Jenson M John Apr 28 '16 at 14:38
  • in a html document: `alert(api("setArray", "test2"));` – Jojo01 Apr 28 '16 at 14:39
  • you shouldn't do it like this. Whatever you want to do with returned data, you should do in the ajax callback function. – Mohit Bhardwaj Apr 28 '16 at 14:40
  • Yes, the 'A' in 'AJAX' stands for 'asynchronous'. The 'api' function will return before the AJAX request completes. See: http://stackoverflow.com/a/36868176/2116171 for a quick explanation. – Michael L. Apr 28 '16 at 14:44
  • Maybe i could try a while loop? – Jojo01 Apr 28 '16 at 14:45
  • @Jojo01 — If I'm interpreting you correctly: No. That would just lock up the event loop (and the browser UI) and prevent the success event from ever being handled. – Quentin Apr 28 '16 at 14:47
  • No, there is nothing synchronous about this code and jquery's ajax handler takes care of notifying you of when the ajax call is completed (by firing off the 'success' function or the `.done` deferred).. Just do like @Mike said and put whatever data handling logic you need in the success callback. – Michael L. Apr 28 '16 at 14:47
  • Ok, well then probably setting a public variable in the ajax callback function would be the best option – Jojo01 Apr 28 '16 at 14:49
  • No, because the variable probably won't be set when you're trying to do things with it. Handle the data in the callback function, or use a promise if you want to pretend it's synchronous. *Please* read the thread that this has been marked a duplicate of. – Michael L. Apr 28 '16 at 14:53
  • Or, you can set `'async': false`, in your ajax options. That way, it will start behaving synchronously and you will be able to handle it in a way you expect. – Mohit Bhardwaj Apr 28 '16 at 14:53
  • Or learn how asynchronous operations and callbacks work and embrace one of the most powerful features of the language. It can be difficult to fully grasp at first, but it's worth it. – Michael L. Apr 28 '16 at 14:54

1 Answers1

0

To get the data:

function api(successCallback) {
  $.ajax({
   //stuff here
   success: successCallback
  });
}

then invoke it using:

api(function(data) {
  console.log(data);
});

ajax calls are asynchronous.

Rhys Bradbury
  • 1,699
  • 13
  • 24