J
J
jurma2018-01-30 12:48:05
JavaScript
jurma, 2018-01-30 12:48:05

How to implement sequential execution of ajax requests?

Good afternoon. I have an ajax request that pulls data from the database on click on an element. For elements, a handler is added, with a request function.
Question: How to add a click handler (with a request function) for elements received from a previous request?
Logic: the user clicks on one of the list of organizations -> vacancies appear -> clicks on a vacancy -> gets details -> ...

const hospitals = document.querySelectorAll(".hospital");
const typeOfDoctors = document.querySelector(".types_of_doctor");

for(let hospital of hospitals) {
  hospital.addEventListener("click", function() {
    getData(typeOfDoctors, `id_hospital=${hospital.id}`);
  });
}

function getData(container, data) {
  console.log(data);
  const xhr = new XMLHttpRequest();
  xhr.open('POST', "process.php");
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {
    if(this.readyState == 4) {
      console.log(xhr.responseText)
      container.innerHTML = xhr.responseText;
    }
  }
  xhr.send(data);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Kalibrov, 2018-01-30
@jurma

You need to catch the click event not on each .hospital element, but on the common parent container and pass the event object to the method, which will contain a link to the specific clicked element in the event property. target . Further, according to the condition, check if this is a .hospital element, then call the necessary method for processing. In jQuery, this is done via the on method:

$( ".parentEleement" ).on( "click", ".hospital", function() {
  console.log($(this));
});

In this case, the event will fire on any dynamically inserted element inside the tracked container.

A
Ainur Valiev, 2018-01-30
@vaajnur

$( "document" ).on( "click", ".el", function() {
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question