Removing MySQL data in real-time with AJAX and JavaScript

Hello, I am currently working on dynamically removing database entries using JS and AJAX without having to refresh the entire page. Here is a snippet from my data.php file:

<?php
require_once('db.php');

if (isset($_GET['list'])) {
   $query = "SELECT * FROM message";
   mysql_query("SET NAMES 'UTF8'");
   $qq=mysql_query($query);
   $i = 1;
   echo '<div id="rezult">';

while($ff = mysql_fetch_array($qq)){
echo '<div id="id'.$ff['id'].'">'.$i++.'. Name: '.$ff['name'].' Message:'.$ff['message'].'</div>';
}
echo '</div>';
}
?>

This code helps me fetch data from a MySQL table in my project:

index.php

function list() { 
$.get('data.php?list=1', function(o) {
            $('#list').html(o);
            });
}

Any suggestions on how to delete a specific entry dynamically without refreshing the page? I attempted to include the following code as a link within the entry, but it seems to cut off when reaching javascript:$.post(.

<a href="javascript:$.post('delete_post.php', { id: '$ff[id]' } );" class='delete_post' title='delete post'>delete post</a>

I appreciate any advice or guidance on this matter.

Answer №1

Just a heads up - be cautious! If someone tries to access your php file data.php?list=ANYNUMBER, they could potentially delete any row. Make sure you have tight security measures in place to prevent this kind of unauthorized access. Using ajax and Jquery might make it simpler.

You can give this a shot:

$.ajax({
  type: "POST",
  url: "list.php",
  data: { list: "1", session_id: session_ID }
}).done(function( msg ) {
  alert( "Data deleted: " + msg );
});

In this code snippet, the session_id represents the value associated with the specific field (like '1' as shown in your example). When a user visits your page, you assign them a unique SESSION_ID. Later, when they try to delete something by clicking a button, compare the session ID you assigned with the server's session_id to ensure that the action is authorized. This helps to prevent malicious attempts from outsiders trying to trigger actions on your list.php file. For further insights, check out: PHP Session Security

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

What could be causing webpack to struggle in locating the loader?

Check out my package.json: { "name": "redux-todo", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "webpack-dev-server" }, "devDependencies": { "babel": "^6.5.2", "babel-loader": "^6.2.5", "bab ...

Ajax always seems to begin its actions at the most inconvenient times, causing

Encountering an issue with AJAX. The problem arises when the code is executed and ajaxString shows up as undefined in the printed output, despite calling the Ajax code before the return statement. Upon attempting to retrieve AJAX post HTML generation and ...

I'm trying to figure out why the console log output keeps printing on this page. Does anyone know why

Update: I have wrapped the function in a custom hook and used a constant variable to store the data rather than using useState. Every time I visit this page, the console continues to output a never-ending list. Why doesn't it just happen once? I only ...

Utilizing Angular JS to execute a callback function upon receiving data from a Web Service

Attempting to incorporate a controller callback function within my service, triggering upon the success of an $http post request. The code snippet below provides a more detailed description. Controller : function UserAccountCtrl (UserService, $rootScope, ...

Using React Native to extract and store JSON data in a state variable

There are two files located in the same directory: Detail.json Base.js Detail.json contains the following data: [ { "id": 1, "name": "A", }, { "id": 2, "name": "B", }, { "id": 3, "name": "C", } ]; Base.js is structu ...

The error message "TypeError: undefined in JavaScript Vue's V-for loop

I created a function that generates an array of objects in this format: getMonthDaysGrid() { const totalLastMonthDays = this.getFirstDayOfMonth().dayNumber; const totalDays = this.month.numberOfDays + totalLastMonthDays; const monthList = Array ...

I am attempting to retrieve JSON data in JavaScript but am seeing a null response in the action class

Having an issue with JSON data being sent through AJAX from the client side. The data is showing as null inside my action class. Here is the JSON string: {"data":[{"id":"","col":1,"row":1,"size_x":1,"size_y":1}, {"id":"","col":1,"row":2,"size_x" ...

Adding elements to a JavaScript array from within a PHP loop

I'm working with a php loop that is outputting geolocation values. I want to save these values in a javascript array so that I can use them to plot points on an HTML5 canvas. How can I achieve this? Here is the php loop: <ul id = "geo-list"> ...

What is the best way to access a variable's value from outside a promise?

I encountered an issue while trying to assign a value to a variable outside of a promise. Despite defining the variable outside the promise, it is showing up as undefined when I check its value. Could someone assist me with this problem by reviewing my co ...

My React setup is causing some problems that I need to address

React is not my strong suit, but I need to test a React application. The issue arises when attempting to run the server using gulp nodemon, resulting in numerous errors. It seems that the application is built on an outdated version of React and some libra ...

What is the best way to make an ajax commenting system function from a separate directory?

I am facing an issue with implementing an ajax commenting system on my website. When I place all the code from the /comment directory directly in the root, everything works fine and the commenting system functions as expected on new pages. However, when I ...

Ways to dynamically update a div with data from a JSON response

I'm currently in the process of developing a search platform. I have three static divs on the search results page that display certain content, all containing similar code. For example: <div id="result" class="card"> <img src="hello.png" ...

Having difficulties with Vue components displaying in Laravel's blade.php file

Let me share my current setup with you: This is the main "Welcome.blade.php" file where I have included relevant information as the file is quite lengthy: <div id='app'> <router-view></router-view> </div> <script src ...

The sorting of objects by Lodash is not accurate

My aim is to arrange objects based on a specific property (price). var arr = [{ name: 'Apple', price: '1.03' }, { name: 'Cherry', price: '0.33' }, { name: &apo ...

Mocking a named class-export in TypeScript using Jest

I have a node module that exports several classes, including one called Client, which I utilize to create clients with various APIs as methods. I'm currently attempting to test my module, which has a dependency on this node module, using Jest. Howeve ...

Storing a Bootstrap form generated through a form builder into a MySQL database

I have created a form using Bootstrap 2 Form Builder and now I am looking to save the form in JSON format into a MySQL database. However, I am unsure of where to begin with this process. I was able to successfully create the form, but saving it for futur ...

Confused about the concept of repeatable-read in relational database management systems

I am feeling confused about the mechanics of repeatable-read in RDBMS systems. My initial understanding was that it was similar to Git branching, where a complete copy of the current database is used. However, I am puzzled by a specific scenario: Tx1 ...

Remove a row without deleting the corresponding value from the overall total displayed on the label using jQuery

I am currently working on a jQuery date picker project with my existing code. I have successfully implemented the ability to clone rows and add years and months. However, when I try to click "add more", it creates another row where I can add dates from and ...

Puppeteer failing to detect dialog boxes

I'm attempting to simulate an alert box with Puppeteer for testing purposes: message = ''; await page.goto('http://localhost:8080/', { waitUntil: 'networkidle2' }); await page.$eval('#value&apos ...

Can MySQL sort by a specific column and then move any entries with a certain value in another column to the end of the list?

I am working with 3 tables named users, warnings, and warningnames. The structure of the tables is as follows: Users(simplified): u_id, username, password, rank Warnings: w_id, wn_id, u_reporter_id, u_reported_id Warningnames: wn_id, warningInfo, warni ...