Raptox
Raptox

Reputation: 11

Mootools Response in variable

I tryed tu put the ajax response in a variable tu use it later but it's not work

this is my code

var retourn;    

var requestData = new Request ({
    url: 'dnscheck.php',
    async:false,
    onComplete: function(response){
        //alert(response); // this work good
        retourn = response;
    }
});

alert(retourn); // shows me undefined

mootools 1.2.4 version

Any idea how to resolve this plaise


After clearing history and trying many time, it work fine thank you Grim

var retourn;    

var requestData = new Request ({
    url: 'dnscheck.php',
    async:false,
    onComplete: function(response){
        //alert(response); // this work good
        retourn = response;
    }
});

requestData.send();
alert(retourn); // work fine

Upvotes: 0

Views: 204

Answers (1)

Grim
Grim

Reputation: 1648

Remember that ajax calls are asynchronous, so the code in your onComplete handler will only be executed when the call returns, while instead your final alert will be executed immediately after the code creating the request (which you must start by calling the send method, btw) - at this time the variable will always be uninitialized.

Edit: didn't notice you used aync: false (which is usually a bad idea btw...) - you still need to send the request though

requestData.send();

Edit(2): Also, it is best not to use the onComplete callback (it is called when the response returns, even before checking what was actually returned) - instead use the onSuccess callback, and be aware that there are many reasons that the response may fail, so you might want to define the onFailure callback as well and do something in there too.

    var retourn;    

    var requestData = new Request ({
        url: 'yoururl.php',
        async:false,
        onSuccess: function(response){
            retourn = response;
        },
        onFailure: function(xhr) {
            retourn = "failed";
        }
    });

    requestData.send();

            alert(retourn);

Upvotes: 1

Related Questions