-1

I have this code (The problem is that i can't get a returned value from result file):

function resultit(id) {
            var res;
            $.ajax({
                url: "result",
                type: 'POST',
                data: "id=" + id,
                success: function (result) {
                    res = result;
                    if (result == 0) {
                        alert('warning', 'FAILED !');
                    } else {
                        alert('danger', 'SUCCESS !');
                    }
                }
            });
            return res;
        } 

alert(resultit(id)); // always undefined

Can you suggest any modification to get the returned value please ? thank you in advance.

rezker
  • 431
  • 4
  • 7

1 Answers1

0

The problem is that your res variable is assigned a value in an asynchronous callback (the ajax success function). The affect of this is that your return res; statement is executed before res is assigned a value.

To get a clearer picture of what's happening try this

function resultit(id) {
  var res;
  $.ajax({
    url: "result",
    type: 'POST',
    data: "id=" + id,
    success: function (result) {
      res = result;
      alert('And this will happen third: ' + res); // ADD THIS LINE
      if (result == 0) {
        alert('warning', 'FAILED !');
      } else {
        alert('danger', 'SUCCESS !');
      }
    }
  });
  alert('This will happen second'); // AND THIS LINE
  return res;
} 

alert('This will happen first: ' + resultit(id)); // AND CHANGE THIS LINE

These 3 alerts will show you the order in which the statements are executing.

There a many solutions to this problem, all of them are outlined in the accepted answer to the question posted by @Andreas above.

Community
  • 1
  • 1
sfletche
  • 47,248
  • 30
  • 103
  • 119