I need to implement a delete function for posts. I'm showing all the posts in a table. I can't seem to find a better way to show all the post.
This is the html:
<table border="1" id="show__posts" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>User Id</th>
<th>Post Id</th>
<th>Post</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JQuery code for loading posts
var loadposts=function(){
$.ajax({
url:"http://localhost:12091/api/post/",
crossdomain: true,
method:"GET",
complete:function(xmlhttp,status){
if(xmlhttp.status==200)
{
var data=xmlhttp.responseJSON;
$("#msg").html(data[0]);
console.log(data[0]);
var str='';
for (var i = 0; i < data.length; i++) {
str += "<tr>";
str += "<td>"+data[i].UserId+"</td>";
str += "<td>"+data[i].PostId+"</td>";
str += "<td>"+data[i].Post1+"</td>";
str += "<td><button
onclick='deletepost("+data[i].PostId+")'>Delete me</button></td>";
str += "</tr>";
}
$("#show__posts tbody").html(str);
}
else
{
$("#msg").html(xmlhttp.status+":"+xmlhttp.statusText);
}
}
});
}
loadposts();
Incomplete JQuery Code for Delete Post
var deletepost=function(){
$.ajax({
url:"http://localhost:12091/api/post/"+deleteid, <--how should I get this id from the table?
method: "DELETE",
header:"Content-Type:application/json",
data:post,
complete:function(xmlhttp, status){
if(xmlhttp.status == 204)
{
alert("Post Deleted");
}
else{
console.log(xmlhttp.status+":"+xmlhttp.statusText);
}
}
})
}
Finally my Code in controller
public IHttpActionResult Delete(int id)
{
postRepository.Delete(id);
return StatusCode(HttpStatusCode.NoContent);
}
Now my questions:
Is there a better way to show posts in webpage except table? I need to show user id, post id, post
how should I get the post ID from html and use it to delete the post?
**
Update: I've completed the delete function like suggested:
var deletepost=function(deleteid){
$.ajax({
url:"http://localhost:12091/api/post/"+deleteid,
method: "DELETE",
header:"Content-Type:application/json",
data:deleteid,
complete:function(xmlhttp, status){
if(xmlhttp.status == 204)
{
alert("Post Deleted");
}
else{
console.log(xmlhttp.status+":"+xmlhttp.statusText);
}
}
})
}
The error that I'm getting:
Uncaught ReferenceError: deletepost is not defined