Ajax Synchronous XMLHttpRequest

4

What should I do in this situation. I have a script where I have to disable in the AJAX function the option: async : false . I do this because it returns a variable in the wrong way, previous to the last one that was requested.

If I put false, it returns the following message:

  

Synchronous XMLHttpRequest on the main thread is deprecated because of   its detrimental effects to the end user's experience. For more help,   check link .

How do I proceed in this type of situation:

var o = 0;
            $.ajax({
                url : url,
                dataType : "json",
                async : false,
                success : function(data){
                    $.each(data, function(i,v){
                        if(g == v.k){
                            o = v.u;
                            return false;
                        }
                    });
                }
            });

alert(o)

If I do not set it to true, it returns 0. If I set it to false it returns the above message. What to do in this situation?

    
asked by anonymous 30.04.2015 / 22:49

1 answer

3

You have to do a Callback . The code does not wait for Ajax to finish, it is asynchronous .

It would look like this:

var o = 0;

$.ajax({
    url : url,
    dataType : "json",
    async : false,
    success : function(data){
        $.each(data, function(i,v){
            if(g == v.k){
                o = v.u;
                recebeValor(o);
            }
        });
    }
});

function recebeValor(result){
    alert(result);
}
    
23.12.2016 / 14:31