-2

I have an ajax request outside the document.addEventListener('DOMContentLoaded'), and I was wondering if I could wait for the ajax request to be completed inside the EventListener (without async:false).

In other words, don´t fire a function inside the EventListener until the ajax request is fully done.

This is my code:

var a;
$.ajax({
    t: "GET",
    url: "file.php"
}).done(function(data){
    a = data;
});

document.addEventListener('DOMContentLoaded', function() {
    //Wait  for ajax request to complete
    someFunction(a);
});
  • This is not possible. An AJAX request and the DOM are two completely separate entities, and their respective events cannot be merged. A workaround would be to always make the AJAX request within DOMContentLoaded, and place whatever you logic you need to run within the callback of that request. – Rory McCrossan Jun 07 '19 at 15:10
  • @RoryMcCrossan the ajax request set a a variable which is used in the EventListener, I'm currently using what you mentioned, but I was wondering if it would be more efficient getting the ajax outside the DOMContentLoaded for time optimization. – Sergio de Propios Jun 07 '19 at 15:13
  • Just set the variable in the callback of the AJAX request then – Rory McCrossan Jun 07 '19 at 15:14
  • @RoryMcCrossan But if the DOMContentLoaded fires before the ajax request, the variable would be empty, or am I wrong? – Sergio de Propios Jun 07 '19 at 15:16
  • 1
    Which is why I previously suggested you make the AJAX request in document.ready. That way the order of events is guaranteed – Rory McCrossan Jun 07 '19 at 15:18
  • 1
    @SergiodePropios That is why you handle it in the callback function. – Michelangelo Jun 07 '19 at 15:20

2 Answers2

0

In most cases you would just put the ajax request inside the handler, but if you really needed to you could use an event emitter.

let eventEmitter = new EventTarget();
let data = null;

function getData() {
  // simulate ajax call
    setTimeout(function() {
      data = "some data"
      eventEmitter.dispatchEvent(new Event('complete'))
    }, 3000)
}

getData();

document.addEventListener('DOMContentLoaded', function() {
    //Wait  for ajax request to complete
    eventEmitter.addEventListener('complete', function() {
      // do something here
      console.log("Ajax request finished");
    })
});
Isaac Vidrine
  • 1,568
  • 1
  • 8
  • 20
-1

You can define a function which returns the ajax promise like so:

function myajax(){
    return $.ajax({
               t: "GET",
               url: "file.php"
           });
var promise = myajax();
document.addEventListener('DOMContentLoaded', function() {
    promise.done(function(data){ 
        //Some action
    }
Heiner Früh
  • 127
  • 5