I have two buttons in a form, and I want to retrieve the data of my method create post to generate a list of the data in a row. The problem is when I reload the page, the list disappear and it reload the page when I click on one of the button.
<script>
document.addEventListener('DOMContentLoaded', function() {
// Load the list of posts from local storage
const posts = JSON.parse(localStorage.getItem('posts')) || [];
// Check each post
posts.forEach((post, index) => {
// AJAX call to check if the post exists
fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
method: 'POST',
body: JSON.stringify({
action: 'check_post',
id: post.id
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
if (data.exists === false) {
// If the post doesn't exist, remove it from the DOM
const pageElement = document.getElementById(post.id);
if (pageElement) {
pageElement.parentNode.removeChild(pageElement);
}
// Remove the post from the list
posts.splice(index, 1);
// Store the updated list of posts in local storage
localStorage.setItem('posts', JSON.stringify(posts));
}
});
});
// Add event listeners to buttons
document.querySelectorAll('button#gutenberg_button, button#elementor_button').forEach(button => {
button.addEventListener('click', function(e) {
e.preventDefault();
const form = this.closest('form'); // Find the closest form to the clicked button
const formData = new FormData(form);
formData.append('action', 'create_post');
fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
// Create table row
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 dateCell = document.createElement('td');
dateCell.textContent = data.date;
const actionsCell = document.createElement('td');
actionsCell.classList.add('actions'); // Add a class for styling
// Create buttons for actions
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
});
const deleteButton = document.createElement('button');
deleteButton.classList.add('deleteBtn');
deleteButton.innerHTML = '<i class="fas fa-trash-alt fa-lg"></i>';
deleteButton.addEventListener('click', () => {
deletePost(data.id); // Call the deletePost function with the post ID
});
const viewButton = document.createElement('button');
viewButton.classList.add('viewBtn');
viewButton.innerHTML = '<i class="fas fa-eye fa-lg"></i>';
viewButton.addEventListener('click', () => {
// Add functionality for viewing the post
});
// Append buttons to actions cell
actionsCell.appendChild(editButton);
actionsCell.appendChild(deleteButton);
actionsCell.appendChild(viewButton);
// Append cells to the table row
tableRow.appendChild(titleCell);
tableRow.appendChild(dateCell);
tableRow.appendChild(actionsCell);
// Get the table body and append the updated row
const tableBody = document.getElementById('generated-pages');
tableBody.appendChild(tableRow);
// Add the new post to the list of posts
posts.push(data);
localStorage.setItem('posts', JSON.stringify(posts));
showNotification();
});
});
});
});
</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();
}
}
}
When i was using document.querySelectorAll('form').forEach(form => { form.addEventListener('submit', function(e) { e.preventDefault();
It worked like that but I can’t select all the form because I have another Button submit on the page, and it will not work after.