I want to create a row in a table when I click on a submit button. The problem I have is that when I want to generate the title and date of the post created, I have undefined. It do not find the data.
I use LocalStorage because when I reload the page I want the list of the row to be displayed, but it doesn’t work. I reload the page and the row disappear.
<script>
document.addEventListener('DOMContentLoaded', () => {
let generatedPosts = JSON.parse(localStorage.getItem('posts')) || [];
// Ajouter un gestionnaire d'événements pour le bouton Gutenberg
document.getElementById('gutenberg_button').addEventListener('click', function(e) {
e.preventDefault();
createNewPost('gutenberg'); // Appel de la fonction pour créer un nouveau post
});
// Ajouter un gestionnaire d'événements pour le bouton Elementor (si nécessaire)
if (document.getElementById('elementor_button')) {
document.getElementById('elementor_button').addEventListener('click', function(e) {
e.preventDefault();
createNewPost('elementor'); // Appel de la fonction pour créer un nouveau post
});
}
// Fonction pour créer un nouveau post via AJAX
function createNewPost() {
let generatedPosts = [];
const formData = new FormData();
formData.append('action', 'create_post');
//formData.append('builder', builder); // Ajouter un paramètre pour indiquer le constructeur utilisé
fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
const postTitle = data.title;
const postDate = data.date;
// Créer une nouvelle ligne du tableau avec les données du post nouvellement créé
const newRow = `
<tr>
<td>${postTitle}</td>
<td>${postDate}</td>
<td>
<button class="editBtn">Editer</button>
<button class="deleteBtn">Supprimer</button>
<button class="viewBtn">Visualiser</button>
</td>
</tr>
`;
// Ajouter la nouvelle ligne au tableau
document.getElementById('generated-pages').insertAdjacentHTML('beforeend', newRow);
// Ajouter le nouveau post à la liste des posts
generatedPosts.push(data);
// Mettre à jour les données locales
localStorage.setItem('generatedPosts', JSON.stringify(generatedPosts));
// Afficher une notification (vous devez définir cette fonction)
showNotification();
//console.log(generatedPosts.map(post => post.title));
});
}
});
</script>
<script>
function showNotification() {
const notification = document.getElementById('notification');
notification.style.display = 'block';
// Masquer la notification après 5 secondes
setTimeout(function() {
notification.style.display = 'none';
}, 5000);
}
function deletePost(postId) {
jQuery.ajax({
url: "admin-ajax.php",
type: "POST",
data: {
action: "delete_post",
id: postId
},
success: function(response) {
if (response === "success") {
// Remove the pageElement
jQuery("#"+postId).remove();
}
}
});
}
</script>
<script>
function deletePostDetails(postId) {
// Remove the title
jQuery("#title-"+postId).remove();
// Remove the date
jQuery("#date-"+postId).remove();
}
</script>
<?php
}
/**
* Create a new post with the content from the JSON file.
*
* @return void
*/
public function create_post()
{
if (!session_id()) {
session_start();
}
// Check if this is an AJAX request
if (defined('DOING_AJAX') && DOING_AJAX && isset($_POST['action']) && $_POST['action'] === 'create_post') {
if (isset($_POST['submit-gutenberg']) && $_POST['submit-gutenberg'] === 'gutenberg') {
// Read the JSON file
$json_data = file_get_contents(__DIR__ . '/partner.json');
// Check if the JSON file was read successfully
if ($json_data === false) {
echo "Erreur de lecture du fichier JSON.";
return;
}
// Decode the JSON data
$block_data = json_decode($json_data, true);
// Check if the JSON data was decoded successfully
if ($block_data === null) {
echo "Erreur lors du décodage du fichier JSON.";
return;
}
// Retrieve the title, content, and sync status from the JSON data
$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';
$img_url = isset($block_data['img_url']) ? $block_data['img_url'] : array();
// Create a new post page
$post_data = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => $sync_status,
'post_type' => 'page', // You can change this as per your requirement
);
// Insert the post into the database
$post_id = wp_insert_post($post_data);
// Check if the post was inserted successfully
if ($post_id) {
// Get the post title and date
$post_title = get_the_title($post_id);
$post_date = get_the_date('Y-m-d', $post_id);
// Prepare the data to be returned as JSON
$new_post_data = array(
'title' => $post_title,
'date' => $post_date
);
// Return the JSON response
header('Content-Type: application/json');
echo json_encode($new_post_data);
} else {
// If post insertion fails, return an error message
echo json_encode(array('error' => 'Failed to insert post.'));
}
// Always remember to terminate the script
wp_die();
}
}
}
Before , I tried to push an element to retrieve the title and the date, it worked like that but I change to add the listener to the click of the button and add the tr for the table