- WordPress :6.4
- Statut : non résolu
- Ce sujet contient 1 réponse, 2 participants et a été mis à jour pour la dernière fois par
mathieu42, le il y a 12 mois.
-
AuteurMessages
-
16 mai 2024 à 19 h 39 min #2472954
Bonjour,
Ma configuration WP actuelle
- Version de PHP/MySQL : 8.3
- Thème utilisé : mon propre plugin
- Extensions en place : Elementor
Problème(s) rencontré(s) :
Bonjour, je cherche à créer un tableau qui m’affichera toutes les pages générées avec le constructeur.
J’ai donc un bouton submit et au clic de celui ci une ligne du tableau s’ajoute avec les éléments : titre, date , constructeur et les actions (visualiser, supprimer, éditer), j’utilise AJAX.
J’ai un problème qui doit provenir de la récupération des données au clic du bouton.
J’ai crée une méthode create_post pour générer la page mais je n’obtiens pas le titre et la date de la page.
Aussi, quand je rafraichis la page ma ligne de tableau disparait mais c’est encore un autre problème.
Voici mon code :
<script>
document.addEventListener('DOMContentLoaded', (event) => {
// Load the list of posts from local storage
const posts = JSON.parse(localStorage.getItem('posts')) || [];
// Function to update page with new post
function updatePageWithNewPost(data, buttonValue,postId) {
// CREATION DU TABLEAU
const tableRow = document.createElement('tr');
tableRow.id = 'post-' + data.id; // Set the id attribute to the post ID
// Create cells for title, date, and actions
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');
// CREATION DU BOUTON VISUALISER
const viewButton = document.createElement('button');
viewButton.classList.add('viewBtn');
viewButton.innerHTML = '<i class="fas fa-eye fa-lg"></i>';
viewButton.dataset.previewUrl = data.previewUrl; // Stocker l'URL de prévisualisation dans un attribut personnalisé
viewButton.addEventListener('click', () => {
// Récupérer l'URL de prévisualisation depuis l'attribut personnalisé
const previewUrl = viewButton.dataset.previewUrl;
// Rediriger l'utilisateur vers l'URL de prévisualisation
window.location.href = previewUrl;
});
// Ajouter le bouton "Visualiser" à la cellule des actions
actionsCell.appendChild(viewButton);
// Create buttons for actions EDIT
const editButton = document.createElement('button');
editButton.classList.add('editBtn');
editButton.innerHTML = '<i class="fas fa-edit fa-lg"></i>';
editButton.addEventListener('click', () => {
// Add functionality for editing the post
});
// CREATION DU BOUTON SUPPRIMER
const deleteButton = document.createElement('button');
deleteButton.classList.add('deleteBtn');
deleteButton.innerHTML = '<i class="fas fa-trash-alt fa-lg"></i>';
deleteButton.dataset.postId = data.id;
deleteButton.addEventListener('click', function() {
const postId = this.dataset.postId; // Retrieve the post ID from the data attribute
const rowToDelete = this.closest('tr'); // Find the closest row to the clicked delete button
if (confirm('Êtes-vous sûr de vouloir supprimer ce post ?')) {
fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'action=delete_post&id=' + postId, // Send the action and post ID in the request body
})
.then(response => response.json())
.then(data => {
if (data === 'success') {
// Successful deletion, remove the row from the table
rowToDelete.remove();
} else {
// Display an error message or handle the error differently
console.error('Erreur lors de la suppression du post');
}
})
.catch(error => {
console.error('Erreur:', error);
});
}
});
// Maintenant que les boutons sont créées, je peux les ajouter à la ligne du tableau
// Append buttons to actions cell
actionsCell.appendChild(viewButton);
actionsCell.appendChild(editButton);
actionsCell.appendChild(deleteButton);
// Append cells to the table row
tableRow.appendChild(titleCell);
tableRow.appendChild(dateCell);
tableRow.appendChild(constructorCell);
tableRow.appendChild(actionsCell);
// Get the table body and append the updated row
const tableBody = document.getElementById('generated-pages');
tableBody.appendChild(tableRow);
}
// Select the buttons
const gutenbergButton = document.getElementById('gutenberg_button');
const elementorButton = document.getElementById('elementor_button');
// Find the closest form ancestor for each button
const gutenbergForm = gutenbergButton.closest('form');
const elementorForm = elementorButton.closest('form');
// Create an array of the forms
const forms = [gutenbergForm, elementorForm];
// Loop through the forms
forms.forEach(form => {
form.addEventListener('submit', function(e) {
e.preventDefault();
// Get the value of the submitted button
const buttonValue = form.querySelector('[type="hidden"]').value;
// Create a FormData object from the form
const formData = new FormData(form);
// Add the action name to the FormData object
formData.append('action', 'create_post');
// AJAX call
fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
method: 'POST',
body: formData
})
// Waits for the response as JSON and converts the response to an object
.then(response => response.json())
// When JSON conversion completed
.then(data => {
const postId = data.post_id; // Get the post ID from the response
updatePageWithNewPost(data, buttonValue, data.id); // Pass the buttonValue to the updatePageWithNewPost function
posts.push(data);
// Show notification
showNotification();
});
});
});J’envoie la méthode create en pièce jointe.
-
Ce sujet a été modifié il y a 12 mois par
ocewp. Raison : pas assez lisible
-
Ce sujet a été modifié le il y a 12 mois par
mathieu42.
Fichiers joints :
Vous devez être connecté pour voir les fichiers joints.19 mai 2024 à 5 h 13 min #2473026d’après ce que vous avez montré, je ne vois pas d’où vient le souci.
n’hésitez pas à mettre le maximum d’informations, pour vous aider il faudrait nous montrer le débugage du code javascript et du code php.
-
AuteurMessages
- Vous devez être connecté pour répondre à ce sujet.