Ajax + подключение внутренних скриптов но грузит все меню опять

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • Ajax + подключение внутренних скриптов но грузит все меню опять

      Вее работает как ajax ? загрузку скриптов подтянул , но все равно грузит все tpl включает меню верхнее и боковое , вроде все правильно .. но поему грузит все не пойму..

      Source Code

      1. <script>
      2. function initMenu() {
      3. document.querySelectorAll('.nav-link').forEach(item => {
      4. item.addEventListener('click', () => {
      5. loadBlock(item.dataset.url, item.dataset.block);
      6. });
      7. });
      8. }
      9. function loadBlock(url, blockId) {
      10. fetch(url)
      11. .then(response => {
      12. if (!response.ok) throw new Error('error');
      13. return response.text();
      14. })
      15. .then(html => {
      16. const parser = new DOMParser();
      17. const doc = parser.parseFromString(html, 'text/html');
      18. const targetBlock = doc.getElementById(blockId);
      19. const contentDiv = document.getElementById('content');
      20. document.querySelectorAll('script[data-dynamic]').forEach(s => s.remove());
      21. if (targetBlock) {
      22. contentDiv.innerHTML = '';
      23. // Клонируем только нужный блок
      24. const blockClone = targetBlock.cloneNode(true);
      25. contentDiv.appendChild(blockClone);
      26. const scripts = blockClone.querySelectorAll('script');
      27. scripts.forEach(script => {
      28. const newScript = document.createElement('script');
      29. newScript.setAttribute('data-dynamic', '');
      30. if (script.src) {
      31. newScript.src = script.src;
      32. newScript.async = script.async;
      33. newScript.defer = script.defer;
      34. } else {
      35. newScript.textContent = script.textContent;
      36. }
      37. document.body.appendChild(newScript);
      38. });
      39. } else {
      40. contentDiv.innerHTML = '<div style="color:red;">Блок с ID "' + blockId + '"</div>';
      41. }
      42. })
      43. .catch(error => {
      44. document.getElementById('content').innerHTML =
      45. '<div style="color:red;">error: ' + error.message + '</div>';
      46. });
      47. }
      48. document.addEventListener('DOMContentLoaded', initMenu);
      49. </script>
      Display All

      The post was edited 1 time, last by DenPUBG ().

    • все решил с отработкой всех скриптов ... осталась одна задача вывести обзор отдельно и по требованию грузить в всплывающие окно , как доработаю поделюсь решением

      Source Code

      1. <script>
      2. function loadPageContent(url) {
      3. fetch(url)
      4. .then(response => response.text())
      5. .then(html => {
      6. const parser = new DOMParser();
      7. const doc = parser.parseFromString(html, 'text/html');
      8. const menu = doc.querySelector('nav, .menu, #menu');
      9. if (menu) {
      10. menu.remove();
      11. }
      12. const mainContent = doc.querySelector('#content, .main-content, article') || doc.body;
      13. mainContent.querySelectorAll('script').forEach(script => script.remove());
      14. const container = document.getElementById('content');
      15. container.innerHTML = mainContent.innerHTML;
      16. const scripts = Array.from(doc.querySelectorAll('script'));
      17. scripts.forEach(oldScript => {
      18. const newScript = document.createElement('script');
      19. if (oldScript.src) {
      20. newScript.src = oldScript.src;
      21. newScript.async = true;
      22. } else {
      23. newScript.textContent = oldScript.textContent;
      24. }
      25. document.body.appendChild(newScript);
      26. });
      27. })
      28. .catch(error => {
      29. console.error('Ошибка загрузки:', error);
      30. document.getElementById('content').innerHTML = '<p>Ошибка загрузки контента</p>';
      31. });
      32. }
      33. </script>
      34. <button onclick="loadPageContent('game.php?page=research')">research</button>
      35. <button onclick="loadPageContent('game.php?page=buildings')">buildings</button>
      Display All

      The post was edited 1 time, last by DenPUBG ().

    • Вопрос я доработал подгрузку в модальное окно, что расширяет дизайн 2moons , осталась одна проблема, как сделать что бы и сам обзор был по умолчанию в такой же загрузке , или это не обязательно ? так как все клики отрабатываются в ajax и все работает по скриптам.
    • when calling you could do &ajax=1 and if you need more data for the template then &ajax=2
      this should deliver the site without menu.
      <button onclick="loadPageContent('game.php?page=buildings&ajax=2')">buildings</button>
    • а как организовать вернее дать понять что есть файл php вот с такими данными , где отключаю вывод в центральной части дублирующего то есть те tpl которые выводят меню и ресурсы, но не совсем понимаю как дать понять системе что есть такой файл php. сам скрипт обработки будет в навигации , а вывод тултипа в новой tpl

      PHP Source Code

      1. <?php
      2. // load_template.php
      3. $template = $_GET['template'] ?? '';
      4. $allowedTemplates = ['template1', 'template2', и так далее/* ... список всех допустимых шаблонов */];
      5. if (in_array($template, $allowedTemplates)) {
      6. // Отключите вывод header/footer
      7. require "templates/{$template}.tpl";
      8. } else {
      9. echo "Шаблон не найден.";
      10. }
      11. ?>
      Display All
    • и так вроде все работает но выдает вот такую ошибку Warning: require(C:\SERVER\domains\test/templates/buildings.tpl): failed to open stream: No such file or directory in C:\SERVER\domains\test\load_template.php on line 9

      вот код // load_template.php
      <?php

      $template = $_GET['template'] ?? '';
      $allowedTemplates = ['buildings', 'research', 'galaxy', /* ... */]; // Без .tpl

      if (in_array($template, $allowedTemplates)) {
      require __DIR__ . "/templates/{$template}.tpl";
      } else {
      echo "Шаблон не найден.";
      }
      ?>

      и вот что располагается в tpl

      <style>
      #modal {
      position: fixed;
      top: 0; left: 0; right: 0; bottom: 0;
      background: rgba(0,0,0,0.7);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
      }

      #modalContentContainer {
      width: 80%;
      max-height: 600px;
      overflow-y: auto;
      background: white;
      padding: 20px;
      box-shadow: 0 0 10px rgba(0,0,0,0.5);
      }

      #closeModal {
      position: absolute;
      top: 10px; right: 10px;
      background: #ff4d4d;
      color: white;
      border: none;
      padding: 8px 12px;
      cursor: pointer;
      }
      </style>
      <ul id="menu">
      <li><a href="#" data-template="game.php?page=buildings">Здания</a></li>
      <li><a href="#" data-template="game.php?page=research">Исследования</a></li>
      <!-- ... -->
      </ul>

      <!-- Модальное окно -->
      <div id="modal" style="display:none;">
      <div id="modalContentContainer"></div>
      <button id="closeModal">Закрыть</button>
      </div>

      {literal}
      <script>
      document.getElementById('menu').addEventListener('click', function(e) {
      if (e.target.tagName === 'A') {
      e.preventDefault();
      const template = e.target.getAttribute('data-template');
      const modal = document.getElementById('modal');
      const container = document.getElementById('modalContentContainer');

      // Извлекаем параметр `page` из строки вида `game.php?page=buildings`
      const urlParams = new URLSearchParams(template.split('?')[1]);
      const page = urlParams.get('page');

      if (page) {
      fetch(`/load_template.php?template=${encodeURIComponent(page)}`)
      .then(response => {
      if (!response.ok) throw new Error('Ошибка загрузки');
      return response.text();
      })
      .then(html => {
      container.innerHTML = html;
      modal.style.display = 'block';
      })
      .catch(err => {
      container.innerHTML = `<p>Ошибка загрузки: ${err.message}</p>`;
      modal.style.display = 'block';
      });
      } else {
      container.innerHTML = `<p>Неверный формат ссылки</p>`;
      modal.style.display = 'block';
      }
      }
      });
      </script>
      {/literal}
    • поправил вот так пути, но все равно не видет
      <?php
      $template = $_GET['template'] ?? '';
      $allowedTemplates = ['buildings', 'research', 'galaxy'];

      if (in_array($template, $allowedTemplates)) {
      $filePath = __DIR__ . "\\styles\\templates\\game\\{$template}.tpl";

      if (file_exists($filePath)) {
      readfile($filePath); // Выводим содержимое файла
      } else {
      echo "❌ Файл {$filePath} не найден!";
      }
      } else {
      echo "Шаблон не найден.";
      }
      ?>
    • $this->getWindow() can be full or ajax or popup

      the template filenames are builded here
      github.com/mimikri/2Moonz/blob…ctGamePage.class.php#L208

      layout.full.tpl for example

      this tpl files compose wich parts are shown in the answer of your request.
      github.com/mimikri/2Moonz/blob…ates/game/layout.full.tpl
      will show all elements from the game. like menu and stuff.

      you can do a own format like myajax, wich delivers the composition you would like to have.

      other option would be to not use smarty make all templating and lang local, and only load jsons for uptdates.
      but this would be some more effort.


      ps: try require "templates/{$template}.tpl";
      relativ path may work
      and check file rights, donno how this is under windows, but when php is run by a user wich don't has the right to open the files then this could happend under linux.
    • Source Code

      1. // Initialize Smarty
      2. $smarty = new Smarty();
      3. // Assign variables to the template
      4. $smarty->assign('title', 'Hello World');
      5. // Render the template (correct method)
      6. $smarty->display('template.tpl');
      7. // Or to get the output as a string:
      8. $output = $smarty->fetch('template.tpl');
      Display All
      .tpl files are processed by smarty

      require would need valid php code in the file.
    • я сейчас пробовал вот такой вариант
      <?php
      $template = $_GET['template'] ?? '';
      $allowedTemplates = ['buildings', 'research', 'galaxy'];

      if (in_array($template, $allowedTemplates)) {
      $prefixes = ['main.', 'page.']; // Проверяем оба префикса
      $filePath = null;

      foreach ($prefixes as $prefix) {
      $tryPath = $_SERVER['DOCUMENT_ROOT'] . "/styles/templates/game/{$prefix}{$template}.tpl";
      if (file_exists($tryPath)) {
      $filePath = $tryPath;
      break;
      }
      }

      if ($filePath) {
      readfile($filePath);
      } else {
      echo "❌ Ни один шаблон не найден для '{$template}'<br>";
      echo "Проверенные пути:<br>";
      foreach ($prefixes as $prefix) {
      echo "- " . $_SERVER['DOCUMENT_ROOT'] . "/styles/templates/game/{$prefix}{$template}.tpl<br>";
      }
      }
      } else {
      echo "Шаблон не найден.";
      }
      ?>


      {literal}
      <style>
      #modal {
      position: fixed;
      top: 0; left: 0; right: 0; bottom: 0;
      background: rgba(0,0,0,0.7);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
      }

      #modalContentContainer {
      width: 80%;
      max-height: 600px;
      overflow-y: auto;
      background: white;
      padding: 20px;
      box-shadow: 0 0 10px rgba(0,0,0,0.5);
      }

      #closeModal {
      position: absolute;
      top: 10px; right: 10px;
      background: #ff4d4d;
      color: white;
      border: none;
      padding: 8px 12px;
      cursor: pointer;
      }
      </style>

      <ul id="menu">
      <li><a href="#" data-template="buildings">Здания</a></li>
      <li><a href="#" data-template="research">Исследования</a></li>
      <li><a href="#" data-template="galaxy">Галактика</a></li>
      </ul>

      <!-- Модальное окно -->
      <div id="modal" style="display:none;">
      <div id="modalContentContainer"></div>
      <button id="closeModal">Закрыть</button>
      </div>
      {/literal}

      {literal}
      <script>
      document.getElementById('menu').addEventListener('click', function(e) {
      if (e.target.tagName === 'A') {
      e.preventDefault();
      const template = e.target.getAttribute('data-template');
      const modal = document.getElementById('modal');
      const container = document.getElementById('modalContentContainer');

      if (template) {
      fetch(`/load_template.php?template=${encodeURIComponent(template)}`)
      .then(response => {
      if (!response.ok) throw new Error('Ошибка загрузки');
      return response.text();
      })
      .then(html => {
      container.innerHTML = html;
      modal.style.display = 'block';
      })
      .catch(err => {
      container.innerHTML = `<p>Ошибка: ${err.message}</p>`;
      modal.style.display = 'block';
      });
      } else {
      container.innerHTML = `<p>Неверный формат ссылки</p>`;
      modal.style.display = 'block';
      }
      }
      });

      document.getElementById('closeModal').addEventListener('click', function() {
      document.getElementById('modal').style.display = 'none';
      document.getElementById('modalContentContainer').innerHTML = '';
      });
      </script>

      в итоге получаю все равно вот это ❌ Ни один шаблон не найден для 'buildings'
      Проверенные пути:
      - C:/SERVER/domains/test/styles/templates/game/main.buildings.tpl
    • голову всю сломал - моя задача используя ajax вывести его через модальное окно и без потери скриптов обернуть в iframe
      отдельно я вчера это реализовал работает все но при перезагрузке все сбрасывает.. поэтому пошел этим путем но споткнулся об путь к файлам
    • я пытаюсь сейчас указать что используем смарти
      <?php
      // Подключаем автозагрузчик Smarty
      require_once 'C:/SERVER/domains/test/includes/libs/Smarty/Smarty.class.php';

      $templateName = $_GET['template'] ?? '';
      $allowedTemplates = ['buildings', 'research', 'galaxy'];

      if (in_array($templateName, $allowedTemplates)) {
      // Инициализируем Smarty
      $smarty = new Smarty();

      // Настройки путей Smarty
      $templateDir = 'C:/SERVER/domains/test/styles/templates/game/';
      $compileDir = 'C:/SERVER/domains/test/styles/templates_c/';
      $cacheDir = 'C:/SERVER/domains/test/styles/cache/';
      $configDir = 'C:/SERVER/domains/test/styles/configs/';

      $smarty->setTemplateDir($templateDir)
      ->setCompileDir($compileDir)
      ->setCacheDir($cacheDir)
      ->setConfigDir($configDir);

      // Проверяем оба возможных префикса
      $prefixes = ['main.', 'page.'];
      $found = false;

      foreach ($prefixes as $prefix) {
      $tplFile = $prefix . $templateName . '.tpl';

      if (file_exists($templateDir . $tplFile)) {
      try {
      // Передаем переменные в шаблон (если нужно)
      $smarty->assign('title', 'Добро пожаловать в ' . ucfirst($templateName));

      // Рендерим шаблон и выводим результат
      echo $smarty->fetch($tplFile);
      $found = true;
      break;
      } catch (Exception $e) {
      echo "Ошибка рендеринга шаблона: " . $e->getMessage();
      exit;
      }
      }
      }

      if (!$found) {
      echo "❌ Ни один шаблон не найден для '{$templateName}'<br>";
      echo "Проверенные пути:<br>";
      foreach ($prefixes as $prefix) {
      echo "- {$templateDir}{$prefix}{$templateName}.tpl<br>";
      }
      }
      } else {
      echo "Шаблон не найден.";
      }

      ?>


      но не уверен что правильный путь я указал к Smarty
    • you could costomize the layout.full.tpl and abstractgamepage

      in abstract gamepage you assign a new value
      $this->assign(['clientmode'=> $_GET['page'] ?? 0]);
      and in
      layout.full.tpl

      you can wrap all things you dont need in
      {if $clientmode != 0} ... {/if}

      this would make the site allways in iframe mode when you build something for example the reloaded page in the iframe would be without the parts in {if $clientmode != 0} ... {/if} cause then a page is set
      , so only when the game.php withput page is loaded, after login or on reload of the page, the hole page is loaded. you can put the iframe in layout.full.tpl the iframe should sit then

      other way
      change
      $this->tplObj->display('extends:layout.'.$this->getWindow().'.tpl|'.$file);
      to

      PHP Source Code: includes/pages/game /AbstractGamePage.class.php

      1. $windowmode = $this->getWindow();
      2. if(isset($_GET['page'])){
      3. $windowmode = 'popup';
      4. }
      5. $this->tplObj->display('extends:layout.'.$windowmode.'.tpl|'.$file);
      like this the page is called in layout.popup.tpl allways, exept after login or on page reload.

      on both ways the scripts should work, as long as you use an iframe and not use js with innerHTML or something.
    • вроде все подключил , но есть проблемы страницу показывает выводит css, но данные нет что я изменил ..

      в файле в корне проекта

      1) load_template.php
      <?php
      // Подключаем автозагрузчик Smarty
      $smartyPath = 'C:/SERVER/domains/test/includes/libs/Smarty/Smarty.class.php';

      if (!file_exists($smartyPath)) {
      die("❌ Файл Smarty не найден по пути: " . $smartyPath);
      }

      require_once $smartyPath;

      if (!class_exists('Smarty')) {
      die("❌ Класс Smarty не найден. Проверьте путь или структуру библиотеки.");
      }

      // Подключаем функции
      $functionsPath = 'C:/SERVER/domains/test/includes/GeneralFunctions.php';

      if (!file_exists($functionsPath)) {
      die("❌ Файл функций не найден по пути: " . $functionsPath);
      }

      require_once $functionsPath;

      $templateName = basename($_GET['template'] ?? '');
      $allowedTemplates = ['fleetTable', 'buildings', 'research', 'galaxy'];

      if (in_array($templateName, $allowedTemplates)) {
      // Инициализируем Smarty
      $smarty = new Smarty();

      // Настройки путей
      $templateDir = 'C:/SERVER/domains/test/styles/templates/game/';
      $compileDir = 'C:/SERVER/domains/test/styles/templates_c/';
      $cacheDir = 'C:/SERVER/domains/test/styles/cache/';
      $configDir = 'C:/SERVER/domains/test/styles/configs/';

      $smarty->setTemplateDir($templateDir)
      ->setCompileDir($compileDir)
      ->setCacheDir($cacheDir)
      ->setConfigDir($configDir);

      // Регистрируем pretty_number()
      $smarty->registerPlugin("modifier", "pretty_number", "pretty_number");

      // Пример данных (замените на реальные данные)
      $fleetList = [
      ['name' => 'Флот 1', 'size' => 100],
      ['name' => 'Флот 2', 'size' => 50],
      ];

      // Инициализируем переменные
      $smarty->assign([
      'title' => 'Флоты',
      'fleetList' => $fleetList ?? [], // Защита от null
      ]);

      // Ищем шаблон
      $prefixes = ['main.', 'page.'];
      $suffixes = ['.default.tpl'];
      $found = false;

      foreach ($prefixes as $prefix) {
      foreach ($suffixes as $suffix) {
      $tplFile = $prefix . $templateName . $suffix;
      $fullPath = $templateDir . $tplFile;

      if (file_exists($fullPath)) {
      try {
      echo $smarty->fetch($tplFile);
      $found = true;
      break 2;
      } catch (Exception $e) {
      echo "❌ Ошибка рендеринга: " . $e->getMessage();
      exit;
      }
      }
      }
      }

      if (!$found) {
      echo "❌ Шаблон не найден.";
      }
      } else {
      echo "Шаблон не найден.";
      }
      ?>
      -------------------------------------------------------------------------
      сделал изменение в AbstractGamePage.class.php

      protected function __construct() {
      if (!AJAX_REQUEST) {
      $this->setWindow('full');
      if (!$this->disableEcoSystem) {
      $this->ecoObj = new ResourceUpdate();
      $this->ecoObj->CalcResource();
      }
      $this->initTemplate();
      } else {
      $this->setWindow('ajax');
      // Добавьте инициализацию данных для AJAX
      $this->initAjaxData();
      }
      }

      private function initAjaxData() {
      // Здесь загрузите и передайте нужные данные в шаблон
      $fleetList = $this->loadFleetList(); // Ваш метод загрузки
      $this->assign('fleetList', $fleetList ?? []);
      }

      пока в main.navigation.tpl добавил
      {literal}
      <style>
      #modal {
      position: fixed;
      top: 0; left: 0; right: 0; bottom: 0;
      background: rgba(0,0,0,0.7);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
      }

      #modalContentContainer {
      width: 80%;
      max-height: 600px;
      overflow-y: auto;
      background: white;
      padding: 20px;
      box-shadow: 0 0 10px rgba(0,0,0,0.5);
      }

      #closeModal {
      position: absolute;
      top: 10px; right: 10px;
      background: #ff4d4d;
      color: white;
      border: none;
      padding: 8px 12px;
      cursor: pointer;
      }
      </style>

      <ul id="menu">
      <li><a href="#" data-template="buildings">Здания</a></li>
      <li><a href="#" data-template="research">Исследования</a></li>
      <li><a href="#" data-template="galaxy">Галактика</a></li>
      <li><a href="#" data-template="fleetTable">Галактика</a></li>
      </ul>

      <!-- Модальное окно -->
      <div id="modal" style="display:none;">
      <div id="modalContentContainer"></div>
      <button id="closeModal">Закрыть</button>
      </div>
      {/literal}

      {literal}
      <script>
      document.getElementById('menu').addEventListener('click', function(e) {
      if (e.target.tagName === 'A') {
      e.preventDefault();
      const template = e.target.getAttribute('data-template');
      const modal = document.getElementById('modal');
      const container = document.getElementById('modalContentContainer');

      if (template) {
      fetch(`/load_template.php?template=${encodeURIComponent(template)}`)
      .then(response => {
      if (!response.ok) throw new Error('Ошибка загрузки');
      return response.text();
      })
      .then(html => {
      container.innerHTML = html;
      modal.style.display = 'block';
      })
      .catch(err => {
      container.innerHTML = `<p>Ошибка: ${err.message}</p>`;
      modal.style.display = 'block';
      });
      } else {
      container.innerHTML = `<p>Неверный формат ссылки</p>`;
      modal.style.display = 'block';
      }
      }
      });

      document.getElementById('closeModal').addEventListener('click', function() {
      document.getElementById('modal').style.display = 'none';
      document.getElementById('modalContentContainer').innerHTML = '';
      });
      </script>

      {/literal}
    • переходит в шаблоны и показывает дизайн - но они пустые без данных ... сразу не увидел ваш ответ , попробовал это доработать - ошибок не выдает, но как я сказал просто пустая страница без вывода данных
      skrinshoter.ru/sVUFxga6zQJ[Blocked Image: https://skrinshoter.ru/sVUFxga6zQJ]

      The post was edited 1 time, last by DenPUBG ().

    • JavaScript Source Code

      1. // Function to handle link interception and AJAX loading
      2. function dielinks() {
      3. // Get all anchor elements in the document [[1]][[3]]
      4. var links = document.getElementsByTagName("a");
      5. for (var i = 0; i < links.length; i++) {
      6. // Check if link meets criteria for AJAX handling:
      7. // - Doesn't use javascript: protocol
      8. // - Has valid href (not empty or #)
      9. // - Doesn't have onclick/onmousedown attributes as strings
      10. if (links[i].href.includes('javascript') !== true &&
      11. links[i].href !== '' &&
      12. links[i].href !== '#' &&
      13. typeof links[i].getAttribute('onclick') === 'object' &&
      14. typeof links[i].getAttribute('onmousedown') === 'object' &&
      15. typeof links[i].getAttribute('onclick') !== 'string') {
      16. // Log matching links for debugging
      17. console.log(i + '+' + links[i].href);
      18. // Add click event listener to handle AJAX navigation
      19. links[i].addEventListener("click", function (evt) {
      20. evt.preventDefault(); // Prevent default navigation
      21. cujax($(this).attr('href'), 0, evt); // Trigger custom AJAX load
      22. }, false);
      23. }
      24. }
      25. }
      26. // Function to calculate mouse position relative to clicked element
      27. function mpf(e) {
      28. if (e == 0) {
      29. mp = 0; // Reset position if no event
      30. } else {
      31. try {
      32. // Get element position and calculate relative coordinates
      33. var rect = e.target.getBoundingClientRect();
      34. var x = Math.floor(e.clientX - rect.left);
      35. var y = Math.floor(e.clientY - rect.top);
      36. mp = x + 'a' + y; // Format as "xay" string
      37. return mp;
      38. } catch (e) {
      39. console.log(e); // Log errors
      40. mp = 1; // Fallback value
      41. }
      42. }
      43. return mp;
      44. }
      45. var sync = 0; // Request lock to prevent concurrent AJAX calls
      46. // Main AJAX content loading function
      47. function cujax(pfad, formu = 0, event = 0) {
      48. mpf(event); // Capture mouse position
      49. if (typeof formu == 'undefined') formu = 0; // Default form parameter
      50. var inhaltdiv = "content"; // Default content container
      51. // Update container based on URL parameters
      52. if (pfad.includes("mini=1") || pfad.includes("page=raport")) {
      53. inhaltdiv = "batreps";
      54. }
      55. // Prevent concurrent requests unless allowed
      56. if (sync != 0 && !pfad.includes("noblock=1")) {
      57. console.log('blocked call ' + sync);
      58. return;
      59. } else {
      60. console.log('unblocked call ' + sync);
      61. sync = 1; // Lock subsequent requests
      62. }
      63. // Create and configure XMLHttpRequest
      64. var xhttp = new XMLHttpRequest();
      65. xhttp.onreadystatechange = function () {
      66. if (this.readyState == 4 && this.status == 200) {
      67. // Handle successful response
      68. var custime = (new Date()).getTime() - cujaxtime;
      69. // Cleanup workers and intervals
      70. if (typeof worker1 !== "undefined" && !pfad.includes("mini=1")) {
      71. try { worker1.terminate(); } catch (e) { console.log('w1 term fehler' + e); }
      72. worker1 = undefined;
      73. }
      74. // Clear unnecessary intervals
      75. if (!pfad.includes("mini=1")) {
      76. for (var i = maxinterval; i <= myVar; i++) {
      77. if (![servertimeint, plaint, uhrzeitint, pleiint, scanint,
      78. ...Object.values(resourceint), intUpdate, countdownint].includes(i)) {
      79. clearInterval(i);
      80. }
      81. }
      82. }
      83. // Update content container
      84. $('#' + inhaltdiv).empty().html(xhttp.responseText);
      85. // Rebind form submissions in new content
      86. document.querySelectorAll(`#${inhaltdiv} form`).forEach(form => {
      87. if (form.action !== window.location.href && !form.onsubmit) {
      88. form.addEventListener("submit", function (evt) {
      89. evt.preventDefault();
      90. cujax($(this).attr('action'), evt.target, evt);
      91. });
      92. }
      93. });
      94. // Rebind links in new content
      95. dielinks(); // Re-run link interception setup
      96. // Cleanup and UI updates
      97. sync = 0;
      98. document.getElementById(inhaltdiv).scrollTop = 0;
      99. // Handle special cases for dialogs
      100. if (pfad.includes("mini=1") || pfad.includes("page=raport")) {
      101. // Initialize jQuery UI dialog with dynamic title
      102. $('#batreps').dialog({
      103. title: der_title,
      104. width: 'auto',
      105. close: function () {
      106. $(this).html('').dialog("option", "hide");
      107. minipath = 0;
      108. }
      109. });
      110. }
      111. // Additional UI and state management
      112. try {
      113. if (!pfad.includes('page=board') && !pfad.includes('page=Com')) {
      114. //ps.update(); // Update UI components
      115. }
      116. if (!pfad.includes('cp=')) {
      117. nachrichtenbox.style.display = "none";
      118. }
      119. } catch (e) {
      120. if (!pfad.includes("popup=1")) throw new Error(e);
      121. }
      122. // Planet change handling
      123. if (pfad.includes("&cp=") && document.getElementById('distmarker')) {
      124. aresslist_sort(); // Refresh address list
      125. }
      126. } else if (this.readyState == 4) {
      127. // Handle failed requests
      128. console.log('exit: ', xhttp.statusText);
      129. sync = 0;
      130. document.body.style.cursor = "unset";
      131. }
      132. };
      133. // Setup request
      134. cujaxtime = new Date().getTime();
      135. document.body.style.cursor = "progress";
      136. // Handle form submissions
      137. if (formu !== 0) {
      138. var formData = new FormData(formu);
      139. xhttp.open("POST", formu.action + '&cujax=1&stime=' + custime + locaplanet + '&mp=' + mp, true);
      140. xhttp.send(formData);
      141. } else {
      142. xhttp.open("GET", pfad + '&cujax=1&stime=' + custime + locaplanet + '&mp=' + mp, true);
      143. xhttp.send();
      144. }
      145. // Network error handling
      146. xhttp.onabort = xhttp.onerror = function () {
      147. console.log('Request failed');
      148. sync = 0;
      149. document.body.style.cursor = "unset";
      150. };
      151. }
      152. // Helper function to load cached scripts using jQuery
      153. function cachedScript(url, options) {
      154. return jQuery.ajax($.extend({
      155. dataType: "script",
      156. cache: true,
      157. url: url,
      158. async: false
      159. }, options));
      160. }
      161. // Specialized form submission handler
      162. function cujaxform(formu, ausga) {
      163. var http = new XMLHttpRequest();
      164. var url = formu.action;
      165. var formData = new FormData(formu);
      166. http.open("POST", url + '&cujax=1', true);
      167. http.onreadystatechange = function () {
      168. if (http.readyState == 4 && http.status == 200) {
      169. $('#' + ausga).html(http.responseText); // Update target element
      170. }
      171. };
      172. http.send(formData);
      Display All
      this is the js i use in cloneuniverse, it will not run in your game out of the box, but it shows how you could handle problems like ongoning intervals wich are in the scripts.
      it changes all links and changes forms so they are working with the ajax system even if they are normal links before.

      but this is just for inspiration

      your templates are empty because you did not load the page wich extends the abstractpage
      for example ShowOverviewPage.class.php
      cause this pages assign the informations for the templates content section.
    • я вывел лог дбавив следующие
      // Проверка данных перед рендерингом
      echo "<pre>";
      print_r([
      'fleetList' => $fleetList ?? null,
      'title' => $smarty->getTemplateVars('title'),
      ]);
      echo "</pre>";
      ?>
      и
      в навигацию
      <pre>
      {if $fleetList === null}
      Переменная fleetList не передана
      {else}
      Тип: {$fleetList|@gettype}
      Содержимое: {$fleetList|@var_export}
      {/if}
      </pre>

      в итоге вышло так

      Warning: count(): Parameter must be an array or an object that implements Countable in C:\SERVER\domains\test\styles\templates_c\7b53daf8216a14cb28b4a8406e047748f19c744d_0.file.page.fleetTable.default.tpl.php on line 260





      Array( [fleetList] => Array ( [0] => Array ( [name] => Флот 1 [size] => 100 ) [1] => Array ( [name] => Флот 2 [size] => 50 ) ) [title] => Флоты)то есть запрос все таки идет .. но вы правы я не все подключил