parm530
10/9/2019 - 5:07 PM

Waiting for AJAX

Waiting for AJAX call to complete RENDERING view:

  • If you have an AJAX call in your complete: callback (or any other AJAX callback methods) that make another AJAX call that goes to a route to render a view and have code below that call that manipulates the DOM:
    • You need to wait for the 1st AJAX call to complete! Otherwise, the next line of code will execute and may change the HTML of the view that you were trying to load
      • Save the 1st AJAX call into a variable: ev1 = functionThatMakesAJAXRequest()
      • Wrap the var into $.when(ev1).then () -> (if using coffeescript)
      • This ensures that ev1 is completed before the lines of code you want to run are ran
$.ajax 
    url: 'routes/blah/blah',
    method: 'GET'
    data: {
        user_name: username
    }
    beforeSend: () ->
        engageSpinner(true)
    error: (e, xhr, data, status) ->
      // lines of code
    success: (results) ->
        event1 = updateView('route') // this function makes an AJAX request to a route that loads content
        $.when(event1).then () ->
            displayRequestMsg("success", "Quote successfully transferred!", something)
    complete: () ->
        engageSpinner(false)