" /> " /> "/>

Issue with Dynamic Page Loading and JS for Subpages

27 Views Asked by At

I'm facing an issue with dynamically loading subpages along with JS dedicated to these subpages.

I have a main template:

<html>
<body>
<div id="menu>
<a href="/user_form">User form</a>
</div>
<div id="main-content"></div>
</body>
</html>

where I load content using a JS function:

function loadPage(page) {
  const pageLoadingSpinner = new LoadingSpinner('loading-spinner');
  pageLoadingSpinner.show();

  const loadContentPromise = new Promise((resolve, reject) => {
      fetch(page, {
          headers: {
              'X-Requested-With': 'XMLHttpRequest'
          }
      })
      .then(response => response.text())
      .then(html => {
          resolve(html);
      })
      .catch(error => {
          reject(error);
      });
  });

  loadContentPromise
      .then(html => {
          setTimeout(() => {
              document.getElementById('main-content').innerHTML = html;
              pageLoadingSpinner.hide();
          }, 200);
      })
      .catch(error => {
          console.error('Error:', error);
          pageLoadingSpinner.hide();
      });
}

Here's an example code for a subpage:

<form id="myForm">
...
</form>
<script src="/static/script.js"></script>

And content of script.js:

$(document).ready(function() {
  $(document).on('submit', '#myForm', function(event) {
    event.preventDefault();
    submitForm(event);
  });
});
function submitForm(event) {
//ajax
}

However, the code in script.js doesn't execute correctly. Unfortunately, event.preventDefault() is not working, and the form is still getting submitted in classic method.

Any insights into why the event.preventDefault() is not functioning as expected would be greatly appreciated.

I'm trying to solve the problem with chatGPT, but it keeps suggesting fancier and fancier random solutions. As far as I can see, the problem is that it dynamically loads the content, which is then not recognised in script.js

Thank you!

0

There are 0 best solutions below