I need an explanation about this code :
page2.php
<?php if (isset($_POST['p'])) { echo $_POST['p'];}
page.php
<body> <button name="bouton" id="bouton"> TEST </button> <script> document.getElementById('bouton').addEventListener("click", function() { var xhr = new XMLHttpRequest(); xhr.open('POST', 'page2.php'); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send('p=2'); xhr.addEventListener('load', function() { /*document.body.innerHTML += xhr.response;*/ document.getElementById('bouton').insertAdjacentHTML('beforebegin', xhr.response); }); }); </script> </body>
It’s a load more script for testing purpose. While this code works fine, if I replace
document.getElementById('bouton').insertAdjacentHTML('beforebegin', xhr.response);
By the comment :
document.body.innerHTML += xhr.response;
The xhr.response file is adding only once. I can’t understand why.
Thanks a lot !
Advertisement
Answer
Setting the innerHTML of the body is replacing the entire body of your document with a new one, the new button does not have a click handler attached to it like the old button so nothing will happen when you try to click it.
For insertAdjacentHTML nothing is replaced, you’re just adding content before the button. The original button is still there and its click handler responds to your clicks with the ajax request.