0

For some business I need use synchronous for Ajax, could someone help me how to use, I find some code like this but not understand what it do.

function getData(productId, storeId) {
  var returnHtml = '';

  jQuery.ajax({
    url: "/includes/unit.jsp?" + params,
    async: false,
    cache: false,
    dataType: "html",
    success: function(html){
      returnHtml = html;
    }
  });

  return returnHtml;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
nnnnMM
  • 59
  • 3
  • 1
    Synchronous Ajax is a horrible thing to do. Instead, you should write code to use the Ajax result asynchronously. The code is not hard once you learn how to do it. You just have to use the Ajax result in a callback rather than in a function return. FYI, the "A" in "Ajax" stands for "Asynchronous" for a reason. – jfriend00 Feb 26 '16 at 02:28
  • `async: false` is deprecated. Browsers specifically *don't* want you to do this. Why do you think that you need to? What's the actual problem you're trying to solve? – David Feb 26 '16 at 02:42
  • See http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call to learn how to use the asynchronous method, instead of trying to use deprecated synchronous AJAX. – Barmar Feb 26 '16 at 02:47

1 Answers1

0

Your code is the standard jQuery ajax code with async property set to false. This forces the ajax call to be synchronous.

function getData(productId, storeId) {
  var returnHtml = '';

  jQuery.ajax({
    url: "/includes/unit.jsp?" + params,
    async: false, // <-- this forces the ajax call to be synchronous.
    cache: false,
    dataType: "html",
    success: function(html){ //<<-- This is where you get the ajax response
      returnHtml = html;
    }
  });

  return returnHtml;
}

Just be aware that synchronous ajax calls are not very performant.

TeaCoder
  • 1,958
  • 13
  • 13