Douglas Pettersson Douglas Pettersson - 3 months ago 11
jQuery Question

jQuery AJAX code does run, but MySQL post does not get deleted

I have an issue with this code, the full Ajax code runs to the end, and fades out the parent of the deletebtn, here is the code of the deletebtn, post and ajax:

$roomQuery = "SELECT * FROM rooms";
$roomResult = mysqli_query($conn, $roomQuery);

while($roomRow = mysqli_fetch_array($roomResult)){
echo "<div class='roomParent'>";
echo "<div class='edit_roomRow'><h1> Rum " . $roomRow['ID'] . "</h1>" . "<h4>" . $roomRow['Description'] . "</h4></div><div name='id' id='removepost' value='" . $roomRow['ID'] . "' class='btn btn-danger delete-btn'>Ta bort</div>";
echo "</div>";



<script type="text/javascript">
var id = $(this).val();
var parent = $(this).parent();

//Ajax call
url: "php/deletepost.php",
data:{ removepost: id },
success: function(){

And here is the PHP code which the ajax data gets sent to:

$deletesql = "DELETE FROM rooms WHERE ID = " . ($_GET['removepost']);
mysqli_query($conn, $deletesql);

Code is gonna be fixed from sql injections etc. later, this is just testing


Note that, you are trying to access <div> attribute as a value in jQuery, you can't get the value of id attribute as like that.


1) You can use data attribute here in your html as:

<div name='id' id='removepost' data-value='" . $roomRow['ID'] . "' class='btn btn-danger delete-btn'>Ta bort</div>

2) Than you need to get values from attribute in jQuery as:

var id = $(this).attr("data-value"); // replace with: var id = $(this).val();

3) In last, very important, use prepared statement instead of direct using the user input, this will help to prevent your code with SQL Injection. If you still want to use $_GET method here than note that, everyone can hit the URL with any removepost.