-1

This functions always returns undefined but the alert is showing the right value.

    function _gesamt()
{
   var link = "speichern.php?gesamt=true";
    //alert(link);
    var req = new XMLHttpRequest();
    req.onreadystatechange = function(){
        //alert("Ready:"+req.readyState);
        if(req.readyState == 4){
            alert(req.responseText);
            return req.responseText;
        }
    }
    req.open("GET",link,false);
    req.send();
}
Liam Schnell
  • 474
  • 8
  • 25

2 Answers2

1

AJAX is asynchronous. So you must use callbacks.

function _gesamt(callback)
{
   var link = "speichern.php?gesamt=true";
    //alert(link);
    var req = new XMLHttpRequest();
    req.onreadystatechange = function(){
        //alert("Ready:"+req.readyState);
        if(req.readyState == 4){
            callback(req.responseText);
        }
    }
    req.open("GET",link,false);
    req.send();
}

_gesamt(function(response) {
    // do your work here
    alert(response);
});
Murat Çorlu
  • 8,207
  • 5
  • 53
  • 78
  • Well, If I just c/p it it is still not running properly. Here is the rest of the code [code]_bp_iframe.default_amount = _gesamt(); /* Donation-amount, integer 1-99 */ [/code] – Liam Schnell Sep 06 '13 at 12:21
0

The return is inside the inner function, so running _gesamt is not supposed to return anything (even setting aside the question of why you would want to issue AJAX requests this way)

alexsh
  • 1,121
  • 8
  • 12