Answer the question
In order to leave comments, you need to log in
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
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));
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question