The page continues to reload even after AJAX has been implemented

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);
?>

Answer №1

Kindly update type="submit" to type="button"

<?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="button" name="delete" value="Delete" id="delete" onclick="delThis(<?php echo $id[$i];?>);" ></td>
</tr>
<?php }?>
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");
    //implement the necessary logic to remove the row here
 };
 xmlhttp.open("POST",page,true);
 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xmlhttp.send(parameters);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The only function that poses a peculiar challenge is the one that utilizes jQuery and AJAX, in my opinion

Working on a classic ASP form that includes multiple dropdowns, three of which are cascading and rely on the previous dropdown. Most of the code functions correctly except for one issue. There is a script tag in the code that initiates the following actio ...

Modifying the attribute of an element inside an array

Presented below is an object: { "_id" : ObjectId("5a8d83d5d5048f1c9ae877a8"), "websites" : [ "", "", "" ], "keys" : [ { "_id" : ObjectId("5a8d83d5d5048f1c9ae877af"), "name ...

Console is displaying a Next.js error related to the file path _next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json

I keep getting an error in the console on my Next.js website. GET https://example.com/_next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json net::ERR_ABORTED 404 I'm puzzled as to why this is happening. Could it be that I'm mishandling the router? ...

JS The clipboardData in ClipboardEvent is perpetually void

I am trying to retrieve files using CTRL+V from the ClipboardEvent in Angular6, but I am encountering an issue where the clipboardData is always empty regardless of whether I test images or text. This problem persists even when tested on the latest release ...

Challenges with PHP jQuery AJAX

I'm facing a jQuery AJAX problem. The issue arises when I call a page through AJAX, it loads correctly but one character - the apostrophe - gets replaced by I don't know why this is happening? Expected output: "of course it’s based on the" C ...

Exploring ways to utilize fetch results within a return statement in React

I have fetched data that is displayed as shown below. Now, I am trying to figure out how to render this fetch in the return statement within the results div. Does anyone have any ideas on how to achieve this? I attempted using a map function because I assu ...

Utilizing spine.js in conjunction with haml

Recently, I've been experimenting with spine.js and delving into its view documentation. In particular, the example using eco as the templating engine left me feeling less than impressed. Personally, I much prefer working with haml for my templating n ...

Ways to consistently stream information from server to browser

I have a file that is constantly being updated with the following contents: id,value,location 1234,pass,/temp/... 234,fail,/temp/r/... 2343,pass,/temp/status/... The file keeps updating for approximately 1 hour by a program. I want to display ...

Issue with Jquery form plugin functionality on Internet Explorer 8

After spending 4 hours trying to figure out this problem.... I have a plugin that uploads photos and returns them to the Tinymce Editor. It works perfectly in Chrome and Firefox, but for some reason, it fails in IE. When I check the developer tools, I see ...

Creating a CSS animation that smoothly slides across the screen and unveils a hidden text/div once the animation is complete

I have been attempting to replicate the captivating CSS animations seen on a particular website: My goal is to imitate how the site: initially reveals a full-screen black div sliding away to the right progressively loads the black background (div ta ...

Validate if a certain value exists within an array of data using NgIf

Is there a way to verify the existence of a value in an array of data? gjhg = [ id, name ] ...

Using regex in JavaScript to perform destructuring assignment

My current task involves reordering a specific string of text, 'Set 1 Total Games Over/Under 9.5', using regex to make it read as 'Under/Over N Giochi Set 1'. The code snippet that achieves this is as follows: let marketLabel = 'S ...

Steps for sending a request to the root resource

I've encountered a problem that stems from my limited knowledge of Express. Despite creating a project with Express, I'm unable to make calls to the root, only to the routes. I suspect the issue lies in my usage of app.use(...). app.js var inde ...

Guide to incorporating d.ts file for enhancing intellisense in VS Code using a method akin to the NPM approach

In my nodejs project (in JS), I find myself relying heavily on node global variables. Despite receiving warnings against using globals, everything works well except for one thing: The lack of intellisense for globals. Every time I need to use a global fu ...

Creating a progress bar for a pandas operation in a web page

I've been searching online for a while now, but I can't seem to find a solution. I have a simple Flask application that takes a CSV file, reads it into a Pandas dataframe, converts it, and outputs a new CSV file. Using HTML, I have successfully m ...

The sidebar navigation is not appearing on Safari and IOS devices

I am facing an issue with my fixed position navbar and sidebar menu buttons on mobile, specifically on IOS and Safari. When clicking on the cart or account buttons, the sidebar menu does not show up. It seems to be a compatibility issue, and I am looking f ...

Leveraging the power of JavaScript Math methods to dictate the Co-ordinates of HTML Canvas .fillRect

Greetings to everyone! I have dedicated my entire evening to understanding how to implement the (Math.floor(Math.random()) function as the coordinates for the .fillRect method on an HTML canvas element. Despite searching through this website and various ...

Come together with Array starting from the specified startIndex and ending at the

I'm curious to know if there is a utility function available that allows for joining arrays while also providing an index. Perhaps Prototype or jQuery already have this feature, but if not, I am willing to create it myself :) What I envision is somet ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...

Having trouble fixing the '@material-ui/lab' error while working with the newest React update?

My goal is to set up a global alert by following this method: Check out the Sandbox Demo Yet, I encounter an issue with the following error message: ERROR in ./src/components/snackbar/Alert.js 5:0-82 Module not found: Error: Can't resolve '@m ...