1

On load event I am calling an ajax get method withing a loop. But while this loop does not end, my ajax call from a click event is not called. The click event is triggered, but not the ajax method. It is only called after the loop is finished. How to overcome this scenario?

 $(document).ready(function () {

    $.each($(".saldo-load"), function (i, x) {

        $.ajax({
            datatype: "json",
            type: "get",
            url: "/revendedor/myMethod/",
            success: function (data) {
                console.log('loop');
               console.log(data)

            }
        });
    });

});
function myCLick() {

    $.ajax({
        datatype: "json",
        type: "get",
        url: "/revendedor/myMethod",
        success: function (data) {
            console.log('click');
            console.log(data)

        }
    });
}
AlvaroCryptogram
  • 398
  • 3
  • 16
  • 1
    add `async : false,` – Alive to die - Anant Apr 20 '18 at 12:14
  • keep in mind each browser has some limitation of http call at a time (simultaneously). so If you try to more than that specific limitation, your http call will always be on hold until any thread gets free. that's the reason building improve performance of the page. – Deepak Sharma Apr 20 '18 at 12:20
  • `async : false` is [not recommended](https://stackoverflow.com/questions/11448011/jquery-ajax-methods-async-option-deprecated-what-now?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa). It is illogical that you interrupt `each` loop ajax calls and call `myClick` function. – Ali Soltani Apr 20 '18 at 13:18

1 Answers1

0

The solution is to use promise capabilities of JQuery, for this use 'then' methods instead of 'success',

jQuery.post( ) .done( ) and success:

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
remi
  • 1
  • I tried, but I think .done .then is not my case, cause I don`t wan`t cascade events, they don`t depend on each other, I just would like the ajax call from click event didn`t need to wait the loop on the load event to be finished. – AlvaroCryptogram Apr 20 '18 at 12:48