-1

Im trying to get a simple "string" from a callback function, and it remains undefined.

this is what Im trying to do:

I have an Ajax called, and its getting an "hello" messege. ->

function Func1(textConent, lineId) {

var op = "3";
var url = "../xxx/xxx.aspx";
var myReutn;

//id, lineId, place, textContent, summaryId

$.post(url, { url: url, op: op, lineId: lineId, textConent: textConent }, function (e) {

    myReutn = e;


});

return myReutn;

}

then I try to fire this function with :

var e = Func1(myText, lineId);

and then alert the "e", but its remains "undefined". why is that ?

thormayer
  • 1,070
  • 6
  • 28
  • 49

3 Answers3

2

Adding to the other answers, it may be a good idea to restructure your code so that you can work with the asynchronous nature of JavaScript.

In your callback function (in the above code, where you assign the variable myReutn), you may want to call a function that does whatever you want to do with that value outside of Func1.

Kevin Schmid
  • 741
  • 5
  • 9
0

The $.post runs asynchronously. That is, it will finish some time after you start it, but your code doesn't sit around waiting for that to happen. At the time you're returning, the callback hasn't run yet.

cHao
  • 84,970
  • 20
  • 145
  • 172
0

$.post is asynchronous, meaning that your call to Func1 will return before the actual HTTP post takes place. Once your scripts have completed, and the HTTP response comes back from the post, then your inline callback will run.

Jacob
  • 77,566
  • 24
  • 149
  • 228