-1

why when i try to return value from function i get undefined? i know i use void function but what happen if i want get value form function like that?

thanks!

 var t = getdata();
 console.dir("test:" + t); -- > undefined

 function getdata() {
            var list = "";
            $.ajax("api/publish",
                { method: "get" })
                .then(function (response) {
                    console.dir(response); --> print the response 
                });
            return list;
        }
liran
  • 75
  • 8
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Tân May 01 '20 at 10:07
  • Your console command runs *before* the ajax reply arrives in the browser. The ajax request is async, that's why you have to use `.then()` and pass a callback function. Example: https://jsfiddle.net/yfqckwzo/ –  May 01 '20 at 10:09

1 Answers1

0

javascript is an asynchronous programming language and you are doing an ajax call so on ajax call by default async will be true so you have to try with async : false on ajax call. Just give try may be it will give luck

mugabits
  • 1,015
  • 1
  • 12
  • 22
Rajan
  • 9
  • 2