0

I understanding form reading many posts were async=false on the ajax request is not really the method for which to ajax requests. However is there a way for me to know the difference decide which one to use or always use async?

I'm currently faced with with a challenge in understanding ajax and ajax with callbacks and when to use callbacks. I have here a button where I click on so that I can have grialicious http://suprb.com/apps/gridalicious/ append the items I need to #my-grid div container. However the ajax request will always run after it returns my items. So the only method for me right now to make this work is to do request.async=false to make it work synchronously. But is this approach the correct way? Or is there a better way to refactor my code?

$('#loadMoreButton').click(function(){
  var $grid = $('#my-grid').gridalicious('append',loadMoreUserFeed());
})


function loadMoreUserFeed(){

  var loadMoreButton = $('#loadMoreButton')
  var items = new Array;

  var request = {

    success: function(response){
      $.each(response.results.items,function(){

        myitem = document.createElement('div');
        myitem.className = 'my-item';

        items.push(myitem)

      }
    },
    error: function(response){
      debugger;
    }
  }

  request.dataType= 'json';
  request.contentType = 'application/json';
  request.data = $(this).serialize();
  request.scriptCharset = "utf-8";
  request.url = '/my_url';
  request.type = "GET";
  request.async = true;

  $.ajax(request);

  return items;

}

I'm getting the following message when I use request.async=false. But when I do request.async=true an empty array will get returned to gridalicious prior to my items list prior to my request finishing.

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

To async or not to async ajax request? When is it acceptable to use async=false? If to chose to stay with async. How should I structure my execution of ajax?

EDIT

The following is a proposed change I've come up with to enable async=true to work:

$('#loadMoreButton').click(function(){

  loadMoreUserFeed()

})


function loadMoreUserFeed(){

  var loadMoreButton = $('#loadMoreButton')
  var items = new Array;

  var request = {

    success: function(response){
      $.each(response.results.items,function(){

        myitem = document.createElement('div');
        myitem.className = 'my-item';

        items.push(myitem)

      }
      $('#my-grid').gridalicious('append',items);
    },
    error: function(response){
      debugger;
    }
  }

  request.dataType= 'json';
  request.contentType = 'application/json';
  request.data = $(this).serialize();
  request.scriptCharset = "utf-8";
  request.url = '/my_url';
  request.type = "GET";
  request.async = true;

  $.ajax(request);

}

But I do not know if this would be the best approach.

EDIT 2

$('#loadMoreButton').click(function(){

  loadMoreUserFeed(makeDivItems)

})


function loadMoreUserFeed(callback){

  var request = {

    success: function(response){
      callback()
    },
    error: function(response){
      debugger;
    }
  }

  request.dataType= 'json';
  request.contentType = 'application/json';
  request.data = $(this).serialize();
  request.scriptCharset = "utf-8";
  request.url = '/my_url';
  request.type = "GET";
  request.async = true;

  $.ajax(request);

}


function makeDivItems(){

  var items = new Array;

  $.each(response.results.items,function(){

    myitem = document.createElement('div');
    myitem.className = 'my-item';

    items.push(myitem)

  }
  $('#my-grid').gridalicious('append',items);
}
user805981
  • 9,979
  • 8
  • 44
  • 64
  • 2
    _"When is it acceptable to use async=false"_ As per the warning - it's best avoided. [The spec says](https://xhr.spec.whatwg.org/#sync-warning) that browsers may _already_ experiment with throwing an error instead of displaying a warning, so it could (at least in theory) stop working at any time. If you then stick with an async request, your question is then a dupe of this one: [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – James Thorpe Feb 24 '16 at 15:28
  • 1
    I can only think of a good way to use sync when the page will unload and the request won't complete. James threw up a good link there. – Train Feb 24 '16 at 15:52
  • @JamesThorpe I added a proposed fix. But I'm not sure if this is best approach. Please let me know your thoughts. – user805981 Feb 24 '16 at 17:29
  • @user805981 While your fix may work, I'd go with the callback approach as documented in the other question. Right now your `loadMoreUserFeed` function is doing too much - it shouldn't need to know about `'#my-grid'` for instance, rather pass back the results through a callback to a function that does know about it. – James Thorpe Feb 24 '16 at 17:30
  • Wherever an async model won't work, which may be when using some legacy stuff or certain browser features. For example, I had a project where users locked resourced when viewing a page and unlocked it when they navigated away or closed the, and we ended up having to synchronizing the unlock request to make it work within `onbeforeunload`. Ultimately, we'll have to redesign that whole feature to avoid this, but we're stuck with it for now. – moribvndvs Feb 24 '16 at 17:32
  • @JamesThorpe I'm not sure what you mean by it shouldn't need to know about `#my-grid` could you please be more specific? is it possible that you show me a snippet or a gist? Thanks! – user805981 Feb 24 '16 at 18:16
  • @JamesThorpe is edit 3 closer to that of what the callback you are saying? – user805981 Feb 24 '16 at 20:37

0 Answers0