-2

I am trying return callback value outside callback function example:

I make the function based in topic: How do I return the response from an asynchronous call?

(function (){

    return getAjaxResult(function(result) { return result; }); 
     //<-- Return Undefined (in console log return correct value)
})();

function getAjaxResult(callback){
    $.ajax({
       url: 'myurl',
       type: 'GET',
        success: function (result) 
        {
           if (result === 'working'){
                callback(result);
          }else if (result === 'notworking'){
                callback('notworking');
          }
        }
      })
 }

Return "Undefined" (in console log return correct value).

I do not know if this is the best option to return an ajax value in callback

Liam
  • 27,717
  • 28
  • 128
  • 190
Slinidy
  • 367
  • 1
  • 4
  • 12
  • 2
    Possible duplicate of [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) – Serge K. Feb 15 '19 at 14:24
  • It was from this topic that I made this code and it did not work – Slinidy Feb 15 '19 at 14:25
  • 1
    `getAjaxResult` is also async so you can't `function(result) { return result; })`, `return result;` isn't going to return how you think it will, for the same reason you can't return in the ajax call. you'd be much better off using promises here than call backs. Read that duplicate again because you haven't understood it correctly. – Liam Feb 15 '19 at 14:31

1 Answers1

1

There are two ways to do this, you can use async false but is deprecated and you can always use a promise:

do a function like this:

function ajaxCallback(id){
  return   $.ajax({
    method: "POST",
    url: "../YourUrl",
    data: {  id: id}
  })
}

then call it like this:

if (id != '')//
{
    ajaxCallback(id)
               .done(function( response ) {
                               //do something with your response
                            });
}

Hope it helps

stan chacon
  • 768
  • 1
  • 6
  • 19
  • How can I return the response to the return ajaxCallBack? – Slinidy Feb 15 '19 at 14:58
  • @Slinidy the response of done is the response of ajaxCallback, done just run when the ajaxCallback function is finished the response you get is the data you want to work, also you can chain a .fail() after the done to handle errors – stan chacon Feb 15 '19 at 15:03
  • What I wanted was this: return ajaxCallback(id) .done(function( response ) { //do something with your response }); <-- Return response – Slinidy Feb 15 '19 at 15:06
  • @Slinidy fill a hidden input with your response inside the done, then you can fill a variable using that input value by his element id – stan chacon Feb 15 '19 at 15:23