Я пытаюсь создать список страниц с помощью AJAX, когда нажимаю кнопку. Когда я нажимаю кнопку, она работает, у меня добавляется новая строка с созданным мной CSS. Но когда я обновляю страницу, строка больше не существует (tr, td..). У меня есть только данные, но нет таблицы, и действия кнопок больше не работают. Но когда я нажимаю кнопку, строка хорошо добавляется, как на изображении:
создать список в таблице
Titre
Date
Constructeur
Actions
document.addEventListener('DOMContentLoaded', (event) => {
function updatePageWithNewPost(data, buttonValue, postId) {
const tableRow = document.createElement('tr');
tableRow.id = 'post-' + data.id;
tableRow.classList.add('custom-table-row');
const titleCell = document.createElement('td');
titleCell.textContent = data.title;
const constructorCell = document.createElement('td');
constructorCell.textContent = buttonValue;
const dateCell = document.createElement('td');
dateCell.textContent = data.date;
const actionsCell = document.createElement('td');
actionsCell.classList.add('actions');
// Create the view button
const viewButton = document.createElement('button');
viewButton.classList.add('viewBtn');
viewButton.innerHTML = '';
viewButton.dataset.previewUrl = data.previewUrl;
viewButton.addEventListener('click', () => {
const previewUrl = viewButton.dataset.previewUrl;
window.location.href = previewUrl;
});
actionsCell.appendChild(viewButton);
// Create the edit button
const editButton = document.createElement('button');
editButton.classList.add('editBtn');
editButton.innerHTML = '';
editButton.addEventListener('click', () => {
const editUrl = '' + data.id;
window.location.href = editUrl;
});
//create the delete button
const deleteButton = document.createElement('button');
deleteButton.classList.add('deleteBtn');
deleteButton.innerHTML = '';
deleteButton.dataset.postId = data.id;
deleteButton.addEventListener('click', function() {
const postId = this.dataset.postId;
const rowToDelete = this.closest('tr');
if (confirm('Êtes-vous sûr de vouloir supprimer ce post ?')) {
fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'action=delete_post&id=' + postId,
})
.then(response => response.json())
.then(data => {
if (data.success) {
rowToDelete.remove();
} else {
console.error('Erreur lors de la suppression du post');
}
})
.catch(error => {
console.error('Erreur:', error);
});
}
});
//create all the buttons in the cell
actionsCell.appendChild(viewButton);
actionsCell.appendChild(editButton);
actionsCell.appendChild(deleteButton);
tableRow.appendChild(titleCell);
tableRow.appendChild(dateCell);
tableRow.appendChild(constructorCell);
tableRow.appendChild(actionsCell);
document.getElementById('generated-pages').appendChild(tableRow);
// Récupérer les lignes au chargement de la page
fetch('?action=fetch_rows')
.then(response => response.json())
.then(response => {
if (response.success) {
response.data.rows.forEach(row => {
updatePageWithNewPost(row, row.constructor, row.id);
});
} else {
console.error('Erreur lors de la récupération des lignes:', response.data);
}
})
.catch(error => {
console.error('Erreur lors de la récupération des lignes:', error);
});
// const tableBody = document.getElementById('generated-pages');
// tableBody.appendChild(tableRow);
//ici pour mettre dans la base de données
//addRowToStorage(data, buttonValue);
}
// Get the buttons and forms to create a new post
const gutenbergButton = document.getElementById('gutenberg_button');
const elementorButton = document.getElementById('elementor_button');
const gutenbergForm = gutenbergButton.closest('form');
const elementorForm = elementorButton.closest('form');
const forms = [gutenbergForm, elementorForm];
forms.forEach(form => {
form.addEventListener('submit', function(e) {
e.preventDefault();
const buttonValue = form.querySelector('[type="hidden"]').value;
const formData = new FormData(form);
formData.append('action', 'create_post');
fetch('', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
updatePageWithNewPost(data, buttonValue, data.id);
showNotification();
fetchRows();
addRowToStorage(data, buttonValue);
});
});
});
и у меня есть метод для создания списка страниц:
public function display_generated_pages()
{
// Récupérer les données de la base de données
global $wpdb;
$generated_pages = $wpdb->prefix . 'custom_table';
$page = $wpdb->get_results("SELECT * FROM $generated_pages");
$generated_pages = get_option('wooster_generated_pages', array());
$updated_pages = array();
foreach ($generated_pages as $page) {
$post = get_post($page['id']);
if ($post) {
if ($post && ($post->post_status == 'draft' || $post->post_status == 'publish')) {
echo '';
echo '' . esc_html($page['title']) . '';
echo '' . esc_html($page['date']) . '';
$constructor = '';
if (isset($_POST['submit-gutenberg']) && $_POST['submit-gutenberg'] === 'Gutenberg') {
$constructor = 'Gutenberg';
} elseif (isset($_POST['submit-elementor']) && $_POST['submit-elementor'] === 'Elementor') {
$constructor = 'Elementor';
}
echo '' . esc_html($constructor) . '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
// Ajoutez la page existante à la liste mise à jour
$updated_pages[] = $page;
} elseif ($post->post_status != 'trash') {
$updated_pages[] = $page;
}
}
}
// Mettez à jour l'option avec la liste des pages existantes
update_option('wooster_generated_pages', $updated_pages);
}
Я пытался добавить AJAX в свой скрипт для хранения строк
function addRowToStorage(data, buttonValue) {
jQuery.ajax({
url: myAjax.ajaxurl,
method: 'POST',
data: {
action: 'add_row',
row_data: JSON.stringify({
id: data.id,
title: data.title,
date: data.date,
buttonValue: buttonValue,
previewUrl: data.previewUrl
}),
},
success: function(response) {
if (!response.success) {
console.error('Erreur lors de l\'ajout de la ligne au stockage:', response.data);
}
},
error: function(error) {
console.error('Erreur lors de l\'ajout de la ligne au stockage:', error);
}
});
}
function fetchRows() {
jQuery.ajax({
url: myAjax.ajaxurl,
method: 'POST',
data: {
action: 'get_rows',
},
success: function(response) {
if (response.success) {
response.data.rows.forEach(row => {
updatePageWithNewPost(row, row.buttonValue, row.id);
});
} else {
console.error('Erreur lors de la récupération des lignes:', response.data);
}
},
error: function(error) {
console.error('Erreur lors de la récupération des lignes:', error);
}
});
}
// Récupérer les lignes au chargement de la page
fetchRows();
и в php:
public function fetch_rows() {
$rows = get_option('custom_table_rows', array());
wp_send_json_success(['rows' => $rows]);
}
public function get_fetch_rows()
{
$generated_pages = get_option('custom_table_rows', array());
wp_send_json($generated_pages);
}
Я не хочу использовать локальное хранилище, сеансы и файлы cookie, поскольку хочу, чтобы они были доступны во всех браузерах.
Для информации: это мой метод создания сообщения.
public function create_post()
{
if (defined('DOING_AJAX') && DOING_AJAX && isset($_POST['action']) && $_POST['action'] === 'create_post') {
$constructor = '';
if (isset($_POST['submit-gutenberg']) && $_POST['submit-gutenberg'] === 'Gutenberg') {
$constructor = 'Gutenberg';
} elseif (isset($_POST['submit-elementor']) && $_POST['submit-elementor'] === 'Elementor') {
$constructor = 'Elementor';
}
$json_data = file_get_contents(__DIR__ . '/partner.json');
if ($json_data === false) {
echo json_encode(array('error' => 'Erreur de lecture du fichier JSON.'));
wp_die();
}
$block_data = json_decode($json_data, true);
if ($block_data === null) {
echo json_encode(array('error' => 'Erreur lors du décodage du fichier JSON.'));
wp_die();
}
$title = isset($block_data['title']) ? $block_data['title'] : '';
$content = isset($block_data['content']) ? $block_data['content'] : '';
$sync_status = isset($block_data['syncStatus']) ? $block_data['syncStatus'] : 'draft';
$post_data = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => $sync_status,
'post_type' => 'page',
);
$post_id = wp_insert_post($post_data);
if ($post_id) {
$post_title = get_the_title($post_id);
$post_date = get_the_date('Y-m-d', $post_id);
// Récupérez les lignes existantes
$existing_rows = get_option('custom_table_rows', array());
// Ajoutez la nouvelle ligne
$new_post_data = array(
'id' => $post_id,
'title' => $post_title,
'date' => $post_date,
'constructor' => $constructor,
'previewUrl' => get_preview_post_link($post_id)
);
$existing_rows[] = $new_post_data;
// Store the post data in the option
$generated_pages = get_option('wooster_generated_pages', array());
$generated_pages[] = $new_post_data;
update_option('wooster_generated_pages', $generated_pages);
$this->save_row_data_to_database($new_post_data);
header('Content-Type: application/json');
echo json_encode($new_post_data);
} else {
echo json_encode(array('error' => 'Failed to insert post.'));
}
wp_die();
}
Подробнее здесь: https://stackoverflow.com/questions/785 ... ot-applied
После обновления моей страницы скрипт не применяется ⇐ Php
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
После обновления моей страницы мой CSS больше не применяется, как сохранить скрипт
Anonymous » » в форуме Php - 0 Ответы
- 16 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Почему мой пользовательский CSS не применяется к индикатору выполнения на моей странице JSP?
Anonymous » » в форуме CSS - 0 Ответы
- 11 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Почему мой пользовательский CSS не применяется к индикатору выполнения на моей странице JSP?
Anonymous » » в форуме CSS - 0 Ответы
- 7 Просмотры
-
Последнее сообщение Anonymous
-