I'm currently trying to make it so I can delete my comments without refreshing the page but since I am new to AJAX I am having some problems. One of the problems I'm facing is that so far I have only used the load()
function to call whole PHP files and not just single function from inside the file.
The second problem is that usually when I load new stuff, they're loaded inside a specifically made div
, but since I'm trying to delete, instead of load, I am not sure how to do it.
This is my PHP code.
echo "<form method='POST' action='".deleteComments($conn)."'>
<input type='hidden' name='id' value='".$row['id']."'>
<button id='delComments' type='submit' name='commentDelete'>Delete</button>
</form>";
function deleteComments($conn) {
if(isset($_POST['commentDelete'])) {
$id = $_POST['id'];
$sql4 = "DELETE FROM comments WHERE id='$id'";
$result4 = mysqli_query($conn, $sql4);
header("Location: index.php");
}
}
You can tried this code hope this code work for you.
<button id='delComments' data-delete-id = '".$row['id']."' type='submit' name='commentDelete'>Delete</button>
Use jquery for this like
var delete_id = $(this).attr("data-delete-id");
$.ajax({
type: "POST",
url: "your_url",
data: ({id: delete_id}),
cache: false,
success: function(data){
alert(data);
}
});
Your commentFunction.php
function deleteComments($conn) {
$delete_id = $_POST['id'];
if(isset($delete_id)) {
$sql4 = "DELETE FROM comments WHERE id='$id'";
$result4 = mysqli_query($conn, $sql4);
echo 'delete comment';
}
}
You can use define this Javascript then you can call it from the different kind of event and perform AJAX in your application. like onClick(),onSelectedIndexChanged(),etc.
<script type="text/javascript">
var HttpObject,vurl;
function genHttpobject() {
if(window.XMLHttpRequest) {
HttpObject=new XMLHttpRequest();
} else if(window.ActiveXObject) {
HttpObject=new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Does not support AJAX..Please use diff Browser");
}
}
function CallingMethod(val1,display_id) {
genHttpobject();
if(HttpObject!=null) {
HttpObject.open("GET",val1,true);
HttpObject.send(null);
HttpObject.onreadystatechange=function() {
if(HttpObject.readyState==4) {
document.getElementById(display_id).innerHTML=HttpObject.responseText
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.