I'm nidhin
I'm nidhin

Reputation: 2662

variable returning undefined value in javascript

I'm using a function like this

function example(){
var a;
$.ajax({
        url:"www.example.com/function",
        type: 'POST',
        success: function(result){
        a=result;
            }
    });

alert(a);
}

I need the variable outside of ajax function

Here I'm getting result as undefined. How can I get the value there. ?

Upvotes: 0

Views: 271

Answers (4)

VenkateshKumar
VenkateshKumar

Reputation: 96

I think you should return the value in the success function itself

function example(){
var a;
$.ajax({
        url:"www.example.com/function",
        type: 'POST',
        success: function(result){
           a=result;
           alert(a);
           return a;
        }
    });
}

Upvotes: 0

mridula
mridula

Reputation: 3283

You can wait for the ajax call to return, by specifying async: false.

function example(){
    var a;
    $.ajax({
        url:"www.example.com/function",
        type: 'POST',
        async: false,
        success: function(result){
            a=result;
        }
    });
    alert(a);
}

Upvotes: 8

Triode
Triode

Reputation: 11359

var a = "I am defined";
$.ajax({
        url:"www.example.com/function",
        type: 'POST',
        success: function(result){
           a=result;
           alert(a);
        }
    });


}

a Will be undefined until the success call back for the ajax is called.

Upvotes: 4

i2ijeya
i2ijeya

Reputation: 16400

Set a default value for the variable a.

Upvotes: -1

Related Questions