0

I'm trying to make an httpost like below. I want the js to work independent from below ajax which is called per 5 seconds. But it's not working async. It behaves as sync. It blocks the js during ajax. Can you please help me to understand the problem ?

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "../Home/GetMobiles",
            data: JSON.stringify(model),
            dataType: "json",
            async: true,
            success: function(data) 
            {
                DivLd.style.display = "none";
                SetMoving(data);
                glob = data;
            },
            error: function(xhr, err) {
                GetToken();
            }
        });
  • What do you mean by "behaves as sync"? Is it because the `SetMoving` function isn't called until after the request completes? – nurdyguy May 21 '18 at 17:00

1 Answers1

0

I think in this case it is not possible to achieve what you're looking for since the JS code that runs after the AJAX request depends on the AJAX response data. You can't have the JS code run until the AJAX request is completed. Even though the request itself is 'asynchronous' to the rest of the JavaScript code (I put asynchronous in quotes because JS in general is not asynchronous -- it may appear to be, but really there is a background queue which processes all JS operations), moving the JS code out of the AJAX response code will not work. Does that answer your question?

Now, having said that, sometimes you might want to run certain operations right before you issue the AJAX request, such as showing a "Loading..." screen or similar. If there are operations you want to happen without waiting for the response data and those operations don't depend on that data, then you can add them right before the $.ajax call.

Andrew
  • 1,581
  • 3
  • 18
  • 31