robind38
robind38

Reputation: 245

Can't set an variable in jquery getjson function?

I want to set an variable in the function after i send an ajax request. What is the reason why the function alert outside the getjson function undefined and inside the good value? Is there some solution?

function gettextlabel(txtvar){ 
    var v = '';
    $.getJSON('http://192.168.0.92/visuals/support/text_handler.php?txtvar=' + txtvar , function(data) {
        v = data;
        alert(v);
    });
    alert(v);
}

Upvotes: 1

Views: 1292

Answers (2)

blaff
blaff

Reputation: 304

This should work:

function gettextlabel(txtvar){ 
    var v = '';

    $.ajax({
        url: 'http://192.168.0.92/visuals/support/text_handler.php',
        data: 'txtvar=' + txtvar,
        type: 'GET',
        dataType: 'json',
        async: false,
        success: function (data) {
            v = data;
            alert(v);
        }
    });

    alert(v);
}

Upvotes: 1

xdazz
xdazz

Reputation: 160843

Because by default jQuery send ajax request asynchronously.

You can set the option async to false to force it work synchronously, like:

$.ajax({
    type: 'GET',
    url: 'http://192.168.0.92/visuals/support/text_handler.php?txtvar=' + txtvar,
    dataType: 'json',
    success: function(data) {  v = data; alert(v); },
    async: false
});

Upvotes: 1

Related Questions