Go to main content

Textpattern CMS support forum

You are not logged in. Register | Login | Help

#1 2024-11-06 09:37:15

astick360
Member
Registered: 2022-05-05
Posts: 23

Site can't render in browser

Hello,

I have a problem about rendering html code with javascript and php on my site.

I added php code and javascript code into forms and try to use them. JavaScript alone, sorta works, slider shows up and html reads correctly.

But as soon as I add php form to the site, the wole html code and JavaScript stops working and displays in one big <pre> tag. Php code works great, it does what it should by taking data from the database as we can see displayed ( i called it in head tag). How to make it work?

Last edited by astick360 (2024-11-07 08:55:25)

Offline

#2 2024-11-06 09:42:52

jakob
Admin
From: Germany
Registered: 2005-01-20
Posts: 4,738
Website

Re: Site can't render in browser

Can you show us how you are including it in your page template or form?

Maybe you just need to wrap it in <txp:php>…</txp:php>. PS: The code printed is missing an opening <script> tag.


TXP Builders – finely-crafted code, design and txp

Offline

#3 2024-11-06 13:21:49

kuopassa
Plugin Author
From: Porvoo, Finland
Registered: 2008-12-03
Posts: 238
Website

Re: Site can't render in browser

Do you have this kind of stuff in the page template:

<txp:header name="Content-Type" value="application/json; charset=utf-8" />

Offline

#4 2024-11-07 08:58:52

astick360
Member
Registered: 2022-05-05
Posts: 23

Re: Site can't render in browser

This is my page code:

<!DOCTYPE html>
<html lang="pl">

<head>
    <meta charset="UTF-8">
    <title>Lista mieszkań</title>
    <txp:css format="link" media="" />
    <txp:output_form form="fetch_data" />
    <txp:output_form form="range_slider" />
</head>

<body>
    <div class="filter-container">
        <!-- Suwak dla powierzchni -->
        <div class="slider-container">
            <label>Powierzchnia:</label>
            <input type="text" id="powierzchnia_min_input" class="value-input" readonly>
            <div class="slider-wrapper">
                <div class="slider-track"></div>
                <div class="slider-range" id="powierzchnia-range"></div>
                <input type="range" id="powierzchnia_min" step="0.01" oninput="updateSlider('powierzchnia')">
                <input type="range" id="powierzchnia_max" step="0.01" oninput="updateSlider('powierzchnia')">
                <span class="slider-value" id="powierzchnia_min_value"></span>
                <span class="slider-value" id="powierzchnia_max_value"></span>
            </div>
            <input type="text" id="powierzchnia_max_input" class="value-input" readonly>
        </div>
        <br>
        <!-- Suwak dla ceny -->
        <div class="slider-container">
            <label>Cena:</label>
            <input type="text" id="cena_min_input" class="value-input" readonly>
            <div class="slider-wrapper">
                <div class="slider-track"></div>
                <div class="slider-range" id="cena-range"></div>
                <input type="range" id="cena_min" step="0.1" oninput="updateSlider('cena')">
                <input type="range" id="cena_max" step="0.1" oninput="updateSlider('cena')">
                <span class="slider-value" id="cena_min_value"></span>
                <span class="slider-value" id="cena_max_value"></span>
            </div>
            <input type="text" id="cena_max_input" class="value-input" readonly>
        </div>
    </div>

    <table id="mieszkaniaTable">
        <thead>
            <tr>
                <th>Mieszkanie / Lokal</th>
                <th>Powierzchnia</th>
                <th>Piętro</th>
                <th>Ilość pokoi</th>
                <th>Cena brutto za m²</th>
                <th>Łączna cena brutto</th>
                <th>Status</th>
                <th>Szczegóły</th>
            </tr>
        </thead>
        <tbody>
            <!-- Wiersze zostaną wygenerowane dynamicznie -->
        </tbody>
    </table>
</body>
</html>

and this is what php form looks like:

<txp:php>
    header('Content-Type: application/json');
    $servername = "localhost";
    $username = "redacted";
    $password = "redacted";
    $dbname = "redacted";
    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT Title, custom_2, custom_3, custom_4, (custom_1 / custom_2) AS cena_m2, custom_1, custom_5 FROM textpattern";
    $result = $conn->query($sql);
    $data = [];

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }

    $rangeQuery = "SELECT MIN AS min_powierzchnia, MAX AS max_powierzchnia, MIN AS min_cena, MAX AS max_cena FROM textpattern";
    $rangeResult = $conn->query($rangeQuery);
    $rangeData = $rangeResult->fetch_assoc();

    $response = [ 
        "data" => $data,
        "ranges" => [ 
            "min_powierzchnia" => (float) $rangeData['min_powierzchnia'],
            "max_powierzchnia" => (float) $rangeData['max_powierzchnia'],
            "min_cena" => (float) $rangeData['min_cena'],
            "max_cena" => (float) $rangeData['max_cena']
        ]
    ];
    echo json_encode($response);
    $conn->close();
</txp:php>

and this is what javascript form looks like:

<script>

// Funkcja do pobierania danych z serwera
function fetchData() { fetch("fetch_data") .then(response => response.json()) .then(responseData => { const data = responseData.data; const ranges = responseData.ranges;

// Ustawienie zakresów dla suwaków setSliderRanges(ranges); populateTable(data); filterTable(); // Filtruj dane po załadowaniu }) .catch(error => console.error("Błąd podczas pobierania danych:", error)); }
// Funkcja do ustawienia zakresów suwaków
function setSliderRanges(ranges) { document.getElementById("powierzchnia_min").min = ranges.min_powierzchnia; document.getElementById("powierzchnia_min").max = ranges.max_powierzchnia; document.getElementById("powierzchnia_max").min = ranges.min_powierzchnia; document.getElementById("powierzchnia_max").max = ranges.max_powierzchnia;

document.getElementById("powierzchnia_min").value = ranges.min_powierzchnia; document.getElementById("powierzchnia_max").value = ranges.max_powierzchnia; document.getElementById("cena_min").min = ranges.min_cena; document.getElementById("cena_min").max = ranges.max_cena; document.getElementById("cena_max").min = ranges.min_cena; document.getElementById("cena_max").max = ranges.max_cena; document.getElementById("cena_min").value = ranges.min_cena; document.getElementById("cena_max").value = ranges.max_cena; // Zaktualizuj widok wartości suwaków updateSlider('custom_2'); updateSlider('custom_1'); }
function populateTable(data) { const tableBody = document.getElementById("mieszkaniaTable").getElementsByTagName("tbody")0; tableBody.innerHTML = ""; // Wyczyszczenie tabeli

if (!data || data.length === 0) { console.log("Brak danych do wyświetlenia"); // DODAJ TO return; } data.forEach(row => { console.log("Dodawanie wiersza:", row); // DODAJ TO const tr = document.createElement("tr"); tr.innerHTML = ` <td>${row.Title}</td> <td>${parseFloat(row.custom_2).toFixed(2)} m²</td> <td>${row.custom_3}</td> <td>${row.custom_4}</td> <td>${parseFloat(row.cena_m2).toFixed(2)} zł</td> <td>${parseFloat(row.custom_1).toFixed(2)} zł</td> <td style="color:${row.custom_5 = 'dostępny' ? 'green' : row.custom_5 = 'rezerwacja' ? 'orange' : 'red'}">${row.custom_5}</td> <td><a href="#">Zobacz</a></td> `; tableBody.appendChild(tr); }); }
// Aktualizacja suwaka i filtrowanie tabeli
function updateSlider(type) { const minSlider = document.getElementById(type + "_min"); const maxSlider = document.getElementById(type + "_max"); const minValue = parseFloat(minSlider.value); let maxValue = parseFloat(maxSlider.value); // Blokada suwaka max na wartości min if (maxValue < minValue) { maxSlider.value = minValue; // Ustaw max na wartość min, jeśli jest niższa } maxValue = parseFloat(maxSlider.value); document.getElementById(type + "_min_value").innerText = minValue.toFixed(2); document.getElementById(type + "_max_value").innerText = maxValue.toFixed(2); document.getElementById(type + "_min_input").value = minValue.toFixed(2); document.getElementById(type + "_max_input").value = maxValue.toFixed(2);

const minPercent = ((minValue – minSlider.min) / (minSlider.max – minSlider.min)) * 100; const maxPercent = ((maxValue – maxSlider.min) / (maxSlider.max – minSlider.min)) * 100; document.getElementById(type + "_min_value").style.left = minPercent + "%"; document.getElementById(type + "_max_value").style.left = maxPercent + "%"; const range = document.getElementById(type + "-range"); range.style.left = minPercent + "%"; range.style.width = (maxPercent – minPercent) + "%"; filterTable(); }
// Filtracja tabeli na bieżąco
function filterTable() { const powierzchniaMin = parseFloat(document.getElementById("powierzchnia_min").value); const powierzchniaMax = parseFloat(document.getElementById("powierzchnia_max").value); const cenaMin = parseFloat(document.getElementById("cena_min").value); const cenaMax = parseFloat(document.getElementById("cena_max").value);

const rows = document.getElementById("mieszkaniaTable").getElementsByTagName("tbody")0.getElementsByTagName("tr"); for (let row of rows) { const custom_2 = parseFloat(row.cells1.innerText.replace(" m²", "")); const custom_1 = parseFloat(row.cells5.innerText.replace(/\s|zł|,/g, "")); const custom_2Match = custom_2 >= powierzchniaMin && custom_2 <= powierzchniaMax; const cenaMatch = !isNaN(custom_1) && custom_1 >= cenaMin && custom_1 <= cenaMax; row.style.display = powierzchniaMatch && cenaMatch ? "" : "none"; } }
// Inicjalizacja aplikacji
fetchData();
</script>

I don’t have the txp:header tag, should I add it?

Last edited by astick360 (2024-11-07 09:25:13)

Offline

#5 2024-11-07 09:02:23

astick360
Member
Registered: 2022-05-05
Posts: 23

Re: Site can't render in browser

Without the “bc..” and “p.” of course, I tried to make it look nice in reply in textile, but can’t figure out why it doesn’t work so I just posted.

Offline

#6 2024-11-07 09:07:16

colak
Admin
From: Cyprus
Registered: 2004-11-20
Posts: 9,092
Website GitHub Mastodon Twitter

Re: Site can't render in browser

astick360 wrote #338159:

Without the “bc..” and “p.” of course, I tried to make it look nice in reply in textile, but can’t figure out why it doesn’t work so I just posted.

fixed it:)


Yiannis
——————————
NeMe | hblack.art | EMAP | A Sea change | Toolkit of Care
I do my best editing after I click on the submit button.

Offline

#7 2024-11-07 10:25:44

jakob
Admin
From: Germany
Registered: 2005-01-20
Posts: 4,738
Website

Re: Site can't render in browser

astick360 wrote #338158:

I don’t have the txp:header tag, should I add it?

I would have thought you should remove that because headers will already have been set for the page.

A couple of thoughts:

  • You’re querying a textpattern table. Is this in the same database? If so, you can skip all the reconnection code as your connection is already active. If it’s in another database on the same site (e.g. same mysql server), you can use rah_swap to switch connections on the fly.
  • If you want to do construct your queries via txp:php, take a look at txp’s built-in database querying functions in /lib/txplib_db.php
  • Alternatively you can use smd_query or etc_query to construct custom queries using txp:style tags.

Finally, if you need to bring in the json with the application/json mime-type, you could put the entire code that constructs the json output into a custom form type. For that, switch on Advanced options in Admin › Preferences and then reload the Admin › Preferences. You’ll see a new section where you can add a new form type under user-defined form types, e.g.

[json]
title="JSON"
mediatype="application/json"

Then create a new form and assign it to the “json” form type. Put your code to generate the json output in that form. In your page template, you can then bring in that form via the url <txp:page_url />?f=form-name and it will be served with the mime-type you specified in the settings.


TXP Builders – finely-crafted code, design and txp

Offline

#8 2024-11-07 17:22:05

kuopassa
Plugin Author
From: Porvoo, Finland
Registered: 2008-12-03
Posts: 238
Website

Re: Site can't render in browser

😉 You should remove this line of PHP code:

header('Content-Type: application/json');

Last edited by kuopassa (2024-11-07 17:22:20)

Offline

Board footer

Powered by FluxBB