guisantogui
guisantogui

Reputation: 4136

JQuery variable problems

i'm having a problem with a variable at my jquery, follow the code:

var resp;
if(itcode != ""){
    resp = $.ajax(
        {url: url_rq}
    );
    resp.done(function () { alert(resp.responseText); });

}

If i put the "resp.responseText" like this above it prints the response, but if i try this code:

var resp;
if(itcode != ""){
    resp = $.ajax(
        {url: url_rq}
    );

}
alert(resp.responseText);

It prints "undefined", what's going on with my "resp" variable?

Upvotes: 2

Views: 89

Answers (4)

Erpheus
Erpheus

Reputation: 826

I think the difference is that when you call

resp.done(function () { alert(resp.responseText); });

it waits for the ajax to return an answer and then prints the variable.

If you change that line for the one outside you will get undefined on both.

The thing is you always have to define a callback for the ajax call to start using its return value. Javascript is asynchronous and will not wait until the request is over.

Upvotes: 0

Mick Sear
Mick Sear

Reputation: 1566

Your Ajax example is asynchronous, so you need to use a callback function (as in your first example) to get and do something with the results. In your second example, you're not using a callback function, so the alert gets triggered before the Ajax call returns.

Upvotes: 2

Simon Wang
Simon Wang

Reputation: 2963

in your second code, when it print the variable, the ajax request was still on the fly, you should not code it like that and only follow the first sample as ajax is asynchronous

Upvotes: 1

Bogdan Emil Mariesan
Bogdan Emil Mariesan

Reputation: 5647

Well since $.ajax is asynchronous it will finish executing after your alert() shows up, so basically in the context of your alert the resp variable is undefined as it hasn't been processed yet by the ajax request.

Upvotes: 0

Related Questions