skip to Main Content

I have a PHP file that I am reloading multiple times into a div with an AJAX call. The fetched PHP file links to an external JavaScript file. The first time I retrieve the file, it works fine. However, when I retrieve the page with the AJAX call for the second time, I’m getting errors that variables have already been declared, which means the script is trying to reload every time I call that file. I can’t attach it to the base page because the initial page is different from the subsequent fetches. Any ideas on how I can attach a JS script to a file that I’m fetching multiple times without errors on conflicting variables?

Here’s a simplified version of my original code:

<head></head>
<body>

<div id='window-change'>
    <?php include('base_page.php'); ?>
</div>

<button id="submit-form">Get results</button>

<script src="script_for_base_page.js"></script>
</body>

I then have an event listener on my button that performs an AJAX call to insert a PHP file that replaces all of the content within the div when the submit form button is clicked. This is the function I attach to the event listener for the ‘search results’ button.

function loadResults() {
  selectedFilters.forEach(obj => {
    var key = Object.keys(obj)[0];
    var value = obj[key];
    pageData[key] = value;    
  });

  $.ajax({
    url: "./ajax/result.php",
    data: {pageData},
    cache: false,
    success: function(data) {
      $("#window-change").html(data);
    }
  });
}

In the fetched result.php file, I have a script tag that loads all the associated JavaScript for that page. After the fetch, my page looks like this:

<head></head>
<body>

<div id='window-change'>
    <button>Next page</button>

    <various html elements with inline javascript via php>

    <script src='./for-ajax-call.js'></script>
</div>

<script src="script_for_base_page.js"></script>
</body>

I now have at this point removed the ‘search results’ button and added a ‘Next Page’ button. This button reloads the same page with updated pageData object that I’m passing in to load the next segment of table data.

The function I’m using for loadResults is pretty much copied inline JavaScript style into my PHP file, and I’m reloading it in nextPage.

function loadResult() {
  $.ajax({
    url: "./ajax/result.php",
    data: {
      pageData: pageDatas
    },
    cache: false,
    success: function(data) {
      $("#window-change").html(data);
    }
  });
}

function nextPage() {
  pageNumber++;
  localStorage.setItem('pageNumber', pageNumber)
  pageDatas['PAGE_SORT'] = localStorage.getItem('pageNumber')
  loadResult()
}

Notice now I’m fetching the same page over and over now just with updated body that I’m sending in with my GET request. However, after pressing the ‘next page’ button and loading the result.php page for a second time, the JavaScript script is reapplied, and I get errors that variables have already been declared, and I’m guessing additional event handlers are being added redundantly as well.

I can’t add the script to the base file or else I get errors that I’m trying to work with HTML elements that don’t exist yet.

Things I’ve tried:

  1. Busting the cache by appending my script with a time signature:
<script src="./js_scripts/categories.js?t=<?php echo time(); ?>"></script>

This didn’t work, and there was no difference.

  1. Adding the script from the base page that I’m loading the content into when the submit-form button is clicked.
let scriptLoaded = false;

document.getElementById('submit-form').addEventListener('click', function() {
  if (scriptLoaded === false) {
    let script = document.createElement('script');
    script.src = './script_for_base_page.js';
    script.id = 'myScript'; // Assign the id here
    setTimeout(() => {
      document.body.appendChild(script);
      scriptLoaded = true;
    }, 500);
  }
});

I don’t get any errors the second time I load the page, but my JavaScript just does not work anymore, with no errors being shown to the console.

  1. Attempted to wrap the entire JavaScript file inside a function, attach it to a window, and call it in the loaded file like such:

(In the JavaScript file)

function loadCategoriesScript(){ All my JS code  }
window.loadCategoriesScript = loadCategoriesScript

Then attach the file and call the function on result.php:

<script src="./script_for_base_page.js"></script>
<script>
  document.addEventListener("DOMContentLoaded", function() {
    loadCategoriesScript();
  })
</script>

This was more of a Hail Mary because I’d never done it before and came across this strategy with desperate searching for a solution. Nothing happened with this, and no script loaded. Intentionally misspelling the file path caused an error, but not with misspelling the function name.

So PLEASE, for the love of everything, help me with this if you can. This bug has been eating away at me. I can’t concentrate on anything else, and no matter how much research I do, I can’t find a way to fix this seemingly trivial bug. Thank you for any help.

2

Answers


  1. I can’t comment yet so I’ll just try to add this as answer.

    It depends on what variables are mentioned in the error that has already been declared.

    The error message "variables have already been declared" typically occurs when you’re declaring a variable that has already been declared in the same scope. This can happen if you’re reloading your JavaScript file multiple times, and the variables you’re declaring are not properly reset or cleared before the script runs again.

    I am assuming that it’s the pageNumber? but you haven’t shown in your code where you set your initial value for pageNumber.

    I come up to this assumption because you are using localStorage to store your pageNumber. It might be one possible cause of your issue. Because when your script reloads, it tries to declare the same variables again without checking if they already exist. Since localStorage persists data even after the page is reloaded, the variables might still exist in the storage, causing the error.

    To avoid this issue, you can check if the variables already exist in localStorage before declaring them. Here’s an example:

    if (localStorage.getItem('myVariable') === null) {
      // Variable doesn't exist, so declare and initialize it
      var myVariable = 'some value';
    } else {
      // Variable already exists in localStorage, so retrieve its value
      var myVariable = localStorage.getItem('myVariable');
    }
    
    Login or Signup to reply.
  2. Try calling the file fetching method on a cron jos, like every 5 seconds, ot utilize something like Signal R

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search