I have created a wordpress addon to add fixtures and results for sports team within different leagues, you can view fixtures and results for each league and delete/edit them as needed.
I have added a button at the end named Delete, and when I click that button I would like it to delete the entry from the table and make the whole entry disappear with a fade.
I have been looking up websites on how ajax works with wordpress but am getting confused.
This is my button code and javascript on the fixtures_admin.php page within my plugin.
<input type="button" id="<?php echo $elementid; ?>" class="submitDeleteEntry" name="submitDeleteEntry" value="Delete" />
<script type="text/javascript">
jQuery(document).on('click', '.submitDeleteEntry', function () {
var id = this.id;
//alert(id);
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "fws_delete_row", "id": id},
success: function (data) {
}
});
});
</script>
The $elementid is just using the variable id from the database and works as intended.
If I uncomment the alert(id); line I do get an alert with the id.
I have placed this code at the top of the page registering the ajax
function fws_delete_row(){
global $wpdb;
$dbtable = $wpdb->prefix . 'fws_fixtures';
$id = $_POST['id'];
$wpdb->delete($table, array('id' => $id));
}
add_action( 'wp_ajax_fws_delete_row', 'fws_delete_row' );
add_action( 'wp_ajax_nopriv_fws_delete_row', 'fws_delete_row' );
But when I click the delete button nothing happens. I have tried looking around the internet for examples of how to do it but can't seem to find the way to do it.
I am happy to come to the conclusion myself but if someone could please explain to me where I am going wrong I would really like to learn.
I know once the delete happens from the database I will need to add more code in for the line to be deleted on the page but for now I just want to get the button at least deleting.
I thank you so much for your help.
I have figured out where I was going wrong, I just had the javascript at the bottom of the file, I had not registered it correctly as indicated in this page https://codex.wordpress.org/AJAX_in_Plugins
I needed to load it into the admin_footer using the code below
add_action( 'admin_footer', 'fws_delete_javascript' );
function fws_delete_javascript() { ?>
<script type="text/javascript">
jQuery(document).on('click', '.submitDeleteEntry', function () {
var id = this.id;
//alert(id);
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "fws_delete_row", "id": id},
success: function (data) {
}
});
});
</script>
<?
}