AJAX button doing nothing in WordPress plugin

I have a simple wordpress plugin to create and delete "Ad campaigns" which are essentially posts in the wordpress database. They submit fine. Problem is, when I try to delete them dynamically using the button in my code the delete button is doing nothing and the POST request isn't sending when I check console. Anyone have any insight on this? This is my full code for reference ** PHP Code** <?php /* Plugin Name: Game Server Ad Campaigns Description: A plugin to allow users to add and display advertisement campaigns for game servers. Version: 1.0 Author: xxxx */ if (!defined('ABSPATH')) { exit; // Exit if accessed directly. } class GameServerAdCampaigns { public function __construct() { add_shortcode('campaign_submission_form', array($this, 'campaign_submission_form_shortcode')); add_shortcode('campaign_list', array($this, 'campaign_list_shortcode')); add_action('init', array($this, 'register_campaign_post_type')); add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts')); add_action('wp_ajax_submit_campaign', array($this, 'submit_campaign')); add_action('wp_ajax_nopriv_submit_campaign', array($this, 'submit_campaign')); add_action('wp_ajax_delete_campaign', array($this, 'delete_campaign')); } public function register_campaign_post_type() { $labels = array( 'name' => 'Campaigns', 'singular_name' => 'Campaign', 'add_new' => 'Add New', 'add_new_item' => 'Add New Campaign', 'edit_item' => 'Edit Campaign', 'new_item' => 'New Campaign', 'all_items' => 'All Campaigns', 'view_item' => 'View Campaign', 'search_items' => 'Search Campaigns', 'not_found' => 'No campaigns found', 'not_found_in_trash' => 'No campaigns found in Trash', 'menu_name' => 'Campaigns' ); $args = array( 'labels' => $labels, 'public' => true, 'has_archive' => true, 'supports' => array('title', 'editor', 'thumbnail'), 'capability_type' => 'post', 'rewrite' => array('slug' => 'campaigns'), ); register_post_type('campaign', $args); } public function campaign_submission_form_shortcode() { if (!is_user_logged_in()) { return 'You need to be logged in to submit a campaign.'; } ob_start(); ?> <div class="campaign-submission-form"> <h2>Submit Your Campaign</h2> <form id="campaign-form"> <input type="text" name="title" id="campaign-title" placeholder="Campaign Title" required><br> <textarea name="description" id="campaign-description" placeholder="Campaign Description" required></textarea><br> <input type="url" name="server_link" id="campaign-server-link" placeholder="Server Link" required><br> <input type="number" step="0.10" name="cost_per_hour" id="campaign-cost-per-hour" placeholder="Cost Per Hour ($)" required><br> <button type="submit">Submit Campaign</button> </form> <div id="campaign-result"></div> </div> <?php return ob_get_clean(); } public function campaign_list_shortcode() { $query = new WP_Query(array( 'post_type' => 'campaign', 'post_status' => 'publish', 'posts_per_page' => -1 )); ob_start(); if ($query->have_posts()) { ?> <div class="campaign-list"> <h2>Campaigns</h2> <ul> <?php while ($query->have_posts()) { $query->the_post(); $server_link = esc_url(get_post_meta(get_the_ID(), 'server_link', true)); $cost_per_hour = get_post_meta(get_the_ID(), 'cost_per_hour', true); $user_id = get_the_author_meta('ID'); $user_info = get_userdata($user_id); $user_name = $user_info->display_name; ?> <li> <h3><?php the_title(); ?></h3> <p><?php the_content(); ?></p> <p>Cost Per Hour: $<?php echo esc_html(number_format($cost_per_hour, 2)); ?></p> <p>Submitted by: <?php echo esc_html($user_name); ?></p> <a href="<?php echo $server_link; ?>" target="_blank">Visit Server</a> <?php if (get_current_user_id() == $user_id) : ?> <button class="delete-campaign-button" data-campaign-id="<?php echo get_the_ID(); ?>">Delete</button> <?php endif; ?> </li> <?php } ?> </ul> </div> <?php } else { echo '<p>No campaigns found.</p>'; } wp_reset_postdata(); return ob_get_clean(); } public function enqueue_scripts() { wp_enqueue_script('jquery'); wp_enqueue_script('campaign-script', plugins_url('script.js', __FILE__), array('jquery'), null, true); wp_localize_script('campaign-script', 'campaign_ajax', array( 'ajax_url' => admin_url('admin-ajax.php') )); wp_enqueue_style('campaign-styles', plugins_url('style.css', __FILE__)); } public function submit_campaign() { if (!is_user_logged_in()) { wp_send_json_error('You need to be logged in to submit a campaign.'); } $user_id = get_current_user_id(); $title = sanitize_text_field($_POST['title']); $description = sanitize_textarea_field($_POST['description']); $server_link = esc_url_raw($_POST['server_link']); $cost_per_hour = floatval($_POST['cost_per_hour']); // Validate cost per hour to ensure it's in increments of 0.10 if ($cost_per_hour <= 0 || fmod($cost_per_hour, 0.10) != 0) { wp_send_json_error('Cost per hour must be a positive number and in increments of $0.10.'); } $campaign_id = wp_insert_post(array( 'post_type' => 'campaign', 'post_title' => $title, 'post_content' => $description, 'post_status' => 'publish', 'post_author' => $user_id, // Save the user ID as the post author )); if ($campaign_id) { update_post_meta($campaign_id, 'server_link', $server_link); update_post_meta($campaign_id, 'cost_per_hour', $cost_per_hour); wp_send_json_success('Campaign submitted successfully.'); } else { wp_send_json_error('There was an error submitting your campaign.'); } } public function delete_campaign() { if (!is_user_logged_in()) { wp_send_json_error('You need to be logged in to delete a campaign.'); } $campaign_id = intval($_POST['campaign_id']); $campaign = get_post($campaign_id); if ($campaign && $campaign->post_type == 'campaign' && $campaign->post_author == get_current_user_id()) { if (wp_delete_post($campaign_id, true)) { wp_send_json_success('Campaign deleted successfully.'); } else { wp_send_json_error('There was an error deleting the campaign.'); } } else { wp_send_json_error('You are not authorized to delete this campaign.'); } } } new GameServerAdCampaigns(); Javascript code jQuery(document).ready(function($) { // Handle form submission $('#campaign-form').on('submit', function(e) { e.preventDefault(); var title = $('#campaign-title').val(); var description = $('#campaign-description').val(); var serverLink = $('#campaign-server-link').val(); var costPerHour = $('#campaign-cost-per-hour').val(); console.log('Submitting campaign:', { title, description, serverLink, costPerHour }); $.post(campaign_ajax.ajax_url, { action: 'submit_campaign', title: title, description: description, server_link: serverLink, cost_per_hour: costPerHour }, function(response) { console.log('Submit campaign response:', response); if (response.success) { $('#campaign-result').html('<p>' + response.data + '</p>'); $('#campaign-form')[0].reset(); } else { $('#campaign-result').html('<p>' + response.data + '</p>'); } }); }); // Handle campaign deletion $(document).on('click', '.delete-campaign-button', function() { if (confirm('Are you sure you want to delete this campaign?')) { var button = $(this); var campaignId = button.data('campaign-id'); console.log('Deleting campaign:', { campaignId }); $.ajax({ type: 'POST', url: campaign_ajax.ajax_url, data: { action: 'delete_campaign', campaign_id: campaignId }, success: function(response) { console.log('Delete campaign response:', response); if (response.success) { button.closest('li').remove(); } else { alert(response.data); } } }); } }); }); Checked console to see if request was sending. Console shows nothing when button clicked. Checked over code multiple times and can't workout why.

Comment (1)

Jese Leos

August 10, 2024

Verified user

On page load you have a code of $('#campaign-form').on('submit', function(e) { //... }); However, if this runs before your form is displayed, then #campaign-form does not exist yet when you are to register DOM listeners to it. This could be a fix if this is a problem: $('body').on('submit', '#campaign-form', function(e) { //... });

You’ll be in good company