jeudi 16 avril 2015

Wordpress plugin interacting with custom table

This is my first foray into the world of Wordpress plugins.


I have managed to create the plugin, activate it and display records from a custom table.


Now I want to be able to add/edit/delete records from href tags using AJAX


This is my code thus far, however, it is not deleting the selected record.


Any help much appreciated.


David



<?php
global $wpdb;
$items = $wpdb->get_results("SELECT * FROM wp_freight;");
echo "<h1>Plate Costs</h1>";
echo "<table class='wp-list-table widefat fixed users'>";
echo "<tr><thead><th>ID</th><th>Origin</th><th>Destination</th><th>Price</th><th></th></tr><thead>";
foreach($items as $item){
echo "<tbody><tr>";
echo "<td>".$item->id."</td>";
echo "<td>".$item->origin."</td>";
echo "<td>".$item->destination."</td>";
echo "<td>".$item->price."</td>";
echo "<td><a class='button button-primary' href='' style='margin-right:10px'>Edit</a><a class='button button-primary' href='#' onclick='ajaxDeleteItem(".$item->id.")'>Delete</a></td>";
echo "</tr></tbody>";
}
echo "</table>";


function delete_row() {
$id = $_POST['element_id'];
$table = 'wp_freight';
$wpdb->delete( $table, array( 'id' => $id ) );
echo $id;
}

add_action('wp_ajax_your_delete_action', 'delete_row');
add_action( 'wp_ajax_nopriv_your_delete_action', 'delete_row');

?>

<script>
function ajaxDeleteItem(a){
var dataString = 'userID='+ a;
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {"action": "your_delete_action", "element_id": a},
success: function(msg){
alert( "Item " + a + " deleted." );
},
error: function(){
alert('failure');
}
});
}
</script>

Aucun commentaire:

Enregistrer un commentaire