1

I have a question to a very common problem. Probably dozens of question have been asked with regard to this. But unfortunately, I am not able to solve my problem. Maybe you can help me! I have the following code:

    function get_network_from_database(callback) {
    $.ajax({
        type: "POST",
        url: "load_network.php",
        data: "json",
        success: callback
    }); 
}

function myCallback(result) {
    return result;
}

var matrix = get_network_from_database(myCallback);

Now, when I alert matrix then it says undefined but when I do alert(get_network_from_database(myCallback)); then it alerts the correct data.

Please could give me a hint what my problem is? All I want is to have the result in the matrix variable.

Thanks a lot in advance!

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
Peter
  • 19
  • 5
  • You can't just "have the result in the matrix variable" at that point, because when your code gets to that point, the result hasn't come back to you yet. The natural next thought is to have your code wait for the result, but you don't want to do that for reasons you will understand once you get your head around asynchronous programming (which you really need to do). Suggest you check out the linked duplicate, and read and re-read it until you understand how it applies to what you're trying to do. – CupawnTae Sep 03 '16 at 15:15

1 Answers1

0

I would be very surprised if alert(get_network_from_database(myCallback)) was giving the correct data. get_network_from_database doesn't return anything.

Ajax requests happen asynchronously. So, whatever you need to do needs to happen in myCallback. i.e. alert(result).

Alternatively you can look into using promises. Change get_network_from_database to return $.ajax(....). Then you should be able to do something like matrix.then(function(result) { alert(result); }) instead of alert(matrix).

  • > I would be very surprised if alert(...) was giving the correct data. `get_network_from_database` doesn't return anything. But it does :-) > Ajax requests happen asynchronously. So, whatever you need to do needs > to happen in myCallback. i.e. `alert(result)`. But I need the staff outside of this function. The question ist how do I get it out of the function? > Alternatively you can look into using promises. I will try. :-) – Peter Sep 03 '16 at 15:19