I'm trying to implement a checkbox that updates my database without reloading the webpage. I asked an AI for help, and got some pretty detailed advice.
I added some js to my webpage and installed and activated a plugin. Code at the end of this post.
The checkbox works nicely enough and the webpage reflects the toggles I do.
But, nothing happens in the database.
I added some logging to see what happens. Only the very first log-command is noted, but the log-attempts in onAfterInitialise and onAjaxCheckboxUpdate are never reached.
Am I missing something obvious, having some simple syntax/spelling-error or somesuch?
Code -----------------------------------
update_checkbox.php
<?php
defined('_JEXEC') or die;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
use Joomla\CMS\Log\Log;
Log::add('Plugin checkbox_update found', Log::INFO, 'ajax'); // Is logged
class PlgSystemCheckboxUpdate extends \Joomla\CMS\Plugin\CMSPlugin
{
public function onAfterInitialise()
{
Log::add('Plugin checkbox_update initialised', Log::INFO, 'ajax');
}
public function onAjaxCheckboxUpdate()
{
Log::add('onAjaxCheckboxUpdate ran', Log::INFO, 'ajax');
// Få JSON-data från förfrågan
$input = Factory::getApplication()->input;
$data = $input->json->getRaw();
// Dekoda JSON
$decoded = json_decode($data, true);
if (!isset($decoded['id']) || !isset($decoded['checked'])) {
echo json_encode(['success' => false, 'error' => 'Invalid data']);
return;
}
$id = (int) $decoded['id'];
$checked = $decoded['checked'] ? 1 : 0;
// Uppdatera databasen
$db = Factory::getDbo();
$query = $db->getQuery(true)
->update($db->quoteName('#__ub_resultattest'))
->set($db->quoteName('is_checked') . ' = ' . $db->quote($checked))
->where($db->quoteName('id') . ' = ' . $db->quote($id));
try {
$db->setQuery($query);
$db->execute();
echo json_encode(['success' => true]);
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
return;
}
}
---------------------------------
From my webpage
$document->addScriptDeclaration('
document.addEventListener("DOMContentLoaded", () => {
const checkbox = document.getElementById("myCheckbox");
const statusText = document.getElementById("status");
checkbox.addEventListener("change", () => {
const isChecked = checkbox.checked;
const dataId = checkbox.getAttribute("data-id"); // ID som används för att identifiera posten i databasen
// Skicka AJAX-förfrågan till servern
fetch("index.php?option=com_ajax&plugin=checkbox_update&format=json", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: dataId, checked: isChecked }),
})
.then(response => response.json())
.then(data => {
if (data.success) {
statusText.textContent = isChecked ? "Checked" : "Unchecked";
statusText.style.color = "green";
} else {
statusText.textContent = "Error";
statusText.style.color = "red";
}
})
.catch(error => {
console.error("Error:", error);
statusText.textContent = "Error";
statusText.style.color = "red";
});
});
});
');
[...]
<div>
<label class="checkbox-label">
<input type="checkbox" id="myCheckbox" data-id="123"> Enable Feature
<span class="status" id="status">Unchecked</span>
</label>
</div>
I added some js to my webpage and installed and activated a plugin. Code at the end of this post.
The checkbox works nicely enough and the webpage reflects the toggles I do.
But, nothing happens in the database.
I added some logging to see what happens. Only the very first log-command is noted, but the log-attempts in onAfterInitialise and onAjaxCheckboxUpdate are never reached.
Am I missing something obvious, having some simple syntax/spelling-error or somesuch?
Code -----------------------------------
update_checkbox.php
<?php
defined('_JEXEC') or die;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
use Joomla\CMS\Log\Log;
Log::add('Plugin checkbox_update found', Log::INFO, 'ajax'); // Is logged
class PlgSystemCheckboxUpdate extends \Joomla\CMS\Plugin\CMSPlugin
{
public function onAfterInitialise()
{
Log::add('Plugin checkbox_update initialised', Log::INFO, 'ajax');
}
public function onAjaxCheckboxUpdate()
{
Log::add('onAjaxCheckboxUpdate ran', Log::INFO, 'ajax');
// Få JSON-data från förfrågan
$input = Factory::getApplication()->input;
$data = $input->json->getRaw();
// Dekoda JSON
$decoded = json_decode($data, true);
if (!isset($decoded['id']) || !isset($decoded['checked'])) {
echo json_encode(['success' => false, 'error' => 'Invalid data']);
return;
}
$id = (int) $decoded['id'];
$checked = $decoded['checked'] ? 1 : 0;
// Uppdatera databasen
$db = Factory::getDbo();
$query = $db->getQuery(true)
->update($db->quoteName('#__ub_resultattest'))
->set($db->quoteName('is_checked') . ' = ' . $db->quote($checked))
->where($db->quoteName('id') . ' = ' . $db->quote($id));
try {
$db->setQuery($query);
$db->execute();
echo json_encode(['success' => true]);
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
return;
}
}
---------------------------------
From my webpage
$document->addScriptDeclaration('
document.addEventListener("DOMContentLoaded", () => {
const checkbox = document.getElementById("myCheckbox");
const statusText = document.getElementById("status");
checkbox.addEventListener("change", () => {
const isChecked = checkbox.checked;
const dataId = checkbox.getAttribute("data-id"); // ID som används för att identifiera posten i databasen
// Skicka AJAX-förfrågan till servern
fetch("index.php?option=com_ajax&plugin=checkbox_update&format=json", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: dataId, checked: isChecked }),
})
.then(response => response.json())
.then(data => {
if (data.success) {
statusText.textContent = isChecked ? "Checked" : "Unchecked";
statusText.style.color = "green";
} else {
statusText.textContent = "Error";
statusText.style.color = "red";
}
})
.catch(error => {
console.error("Error:", error);
statusText.textContent = "Error";
statusText.style.color = "red";
});
});
});
');
[...]
<div>
<label class="checkbox-label">
<input type="checkbox" id="myCheckbox" data-id="123"> Enable Feature
<span class="status" id="status">Unchecked</span>
</label>
</div>
Statistics: Posted by Natrixx — Sat Dec 14, 2024 4:41 pm