0

I am trying to execute specific JavaScript Code after Ajax Content Load. Please allow me to elaborate it. I have Following Code:-

index.html

<table>
<tbody id="tbody"></tbody>
</table>

script.js

// Ajax call, getting data from database 
........
xhr.onload = () => {
x = xhr.response;
for (i = 0; i < x.length; i++) {
tbody.innerHTML += "<tr><td>" + x[i].name + "</td><td> <button class='btn btn-warning btn-sm btn-del' data-sid=" + x[i].id + ">Delete</button></td></tr>";
};
xhr.send();

// I want to execute below code after above ajax content load so i could get the length and can alert each button id
window.onload = function () {
  var x = document.getElementsByClassName("btn-del");
  console.log(x, x.length);
  for (let i = 0; i < x.length; i++) {
    alert(x[i].getAttribute("data-sid"));
  }
};

//This works fine but This is not a good solution.
setTimeout(() => {
  var x = document.getElementsByClassName("btn-del");
  console.log(x, x.length);
  for (let i = 0; i < x.length; i++) {
    alert(x[i].getAttribute("data-sid"));
  }
}, 2000);

I tried below codes but didn't get result as i am expecting:-

window.onload = function () { ......};
window.addEventListener("DOMContentLoaded", function () {.... });
document.onload = function () {...... };
if (document.readyState === 4) { ...... }

Note - I am trying to achieve this with Vanilla JavaScript so Please avoid Jquery

Johnny
  • 21
  • 3
  • https://stackoverflow.com/a/61748773/5947043 – ADyson Jul 03 '20 at 09:26
  • "I want to execute below code after above ajax content load" ...so put it in the "xhr.onload" event of your AJAX call. Any code which must execute after the AJAX has to go in that function (or in a function which is called by the onload function). P.S. I put the link above to show you a more modern way of doing things rather than using old-fashioned XHR. – ADyson Jul 03 '20 at 09:30
  • @ADyson "I want to execute below code after above ajax content load" Actually in this part there will be Ajax Call for Deleting record and i do not want to mix it with "Ajax call, getting data from database" Part. I am looking for old-school if i didn't get any other solution i will create function for "I want to execute below code after above ajax content load" this part and i will call it there as you said. – Johnny Jul 03 '20 at 09:39
  • Yes, separating into different functions and then calling one from the other would be a good idea. It would be a good idea even if the code wasn't asynchronous. – ADyson Jul 03 '20 at 09:42

0 Answers0