Ajax Synchronous Xmlhttprequest

Asked

Viewed 1,005 times

4

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

If I set false, return 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 in http://xhr.spec.whatwg.org/.

How I proceed in this kind 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 to true, it returns 0. If I set to false it returns the above message. What to do in this situation?

  • 3

    Asynchronous requests are deprecated in modern browsers, so you get this message. Find information about callbacks and predecessors to solve your variable problem asynchronously.

  • https://xhr.spec.whatwg.org/#Sync-Warning

  • 1

    Minor correction: @Oeslei meant "synchronous requests" are deprecated...

  • They are various ajax calls and they must follow an order to execute?

  • @Onaiggac It’s been a long time since this question, but I believe at the time it was within a requision, and the return should be as the search goes, I can’t remember if it was ajax or each that wasn’t proceeding with the order (I believe it’s ajax, because each doesn’t do it). If I’m not mistaken, I used .done().

1 answer

3

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

Would that be:

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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.