StreetCoder
StreetCoder

Reputation: 10061

getting error for using async: false

I need to store some data outside ajax call in a variable. So, I am using async: false option in ajax. But it gives me an error:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

See my code below:

var internal_tags = null;

$.ajax({
    async: false,
    dataType:'json',
    contentType:'application/json',
    url: '/ajax-search-suggestions',
    type: 'GET',
    success: function(data) {
        asignVariable(data);
    }
});

// get internal tags
function asignVariable(data){
    internal_tags = data;
}

I need to save ajax success data into internal_tags variable. If I remove the option async: false, data are not saved in variable. So how I can remove the error or how to save ajax success data in the variable which is outside of ajax.

Upvotes: 1

Views: 1088

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You should not use async: true. You should refactor your code so that your functions do not return values but rather take callbacks.

Example of what you should not be doing:

var internal_tags = null;

function getValue() {
    $.ajax({
        async: false,
        dataType:'json',
        contentType:'application/json',
        url: '/ajax-search-suggestions',
        type: 'GET',
        success: function(data) {
            internal_tags = data;
        }
    });
}

And here's the correct approach:

function getValue(callback) {
    $.ajax({
        dataType:'json',
        contentType:'application/json',
        url: '/ajax-search-suggestions',
        type: 'GET',
        success: function(data) {
            callback(data);
        }
    });
}

so instead of:

var internal_tags = null;
getValue();
alert(internal_tags);

you should do this:

getValue(function(internal_tags) {
    alert(internal_tags);
});

I also recommend you looking at jQuery's deferred objects.

Upvotes: 1

Related Questions