I am working on a functionality to delete a row from the database using AJAX. Although the records are successfully being deleted, there is an issue with the page reloading which should not happen when using AJAX. Below is the JavaScript function I am using:
function delThis(id)
{
var deleteRow = id;
var page = "stu_rec1.php";
var parameters ='deleteRow='+deleteRow;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert("Form sent successfully");
};
xmlhttp.open("POST",page,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
}
}
Here is the HTML code snippet:
<?php for($i=0;$i<count($id);$i++){?>
<tr>
<td><?php echo $name[$i];?></td>
<td><?php echo $email[$i];?></td>
<td><?php echo $mobno[$i];?></td>
<td><?php echo $gender[$i];?></td>
<td><?php echo $address[$i];?></td>
<td><input type="submit" name="delete" value="Delete" id="delete" onclick="delThis(<?php echo $id[$i];?>);" ></td>
</tr>
<?php }?>
And here is the PHP code handling the deletion process:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="myDB";
$delete = $_POST["deleteRow"];
$conn = new mysqli($servername, $username, $password,$db);
if ($conn->connect_error) {
die("Connection failed: ".mysqli_connect_error());
}
$sql = "SELECT name, email, mobileno, gender, address FROM studentrecords";
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($delete !="")
{
$query= "DELETE FROM studentrecords WHERE id='$delete'";
$result1 = mysqli_query($conn, $query);
}
mysqli_close($conn);
?>