Jump to content

Deleting record with ajax, php, mysql


PNewCode

Recommended Posts

I chose the php help because the before and after of this process is php

I have a successful way to add entries to the database without leaving the page using ajax and php. I tried to change it up to use it to delete a record in the same way with zero success. After several days of searching and trying, below is what I have come to. Can someone please help me out? Thank you so much :)

What is happening currently, is nothing. No errors, or action. The page just "blinks" like a refresh and adds a # at the end of the URL

action.js

$(document).ready(function() { $('#manage_delete_post').submit(function(e) { e.preventDefault() 
$.ajax({ url: 'delete-post-2.php?id=".$row['id']."', data: $(this).serialize(), method: 'POST', 
success: function(resp) { $('#error_msg_back').html(resp); } }) }) }) 


The page with the delete button (placed in the row with the id of the entry)
index.php

<form action="#" method="post" id="manage_delete_post"> <div class="form-group"> <button class="btn btn-success button pointer" type="submit"><img src="btn/trash12.png" width="32"></button> </div></form>

<script src="action.js"></script>


And here is the delete-post-2.php

<script>
document.addEventListener('contextmenu', event => event.preventDefault());
</script>


<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);


$servername = "localhost";
$username = "stuff";
$password = "stuff";
$dbname = "stuff";


$id = $_GET['id'];


$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// sql to delete a record
$sql = "DELETE FROM livechat_chat WHERE id = $id"; 

$results = mysqli_query($connection, $sql);

if($results) {
    echo "<div id='hideMe'>CHANGES ARE SAVED!</div>";
} else {
    echo "<div id='hideMe'>Changes failed, Please Try Again</div>";
}

 

Link to comment
Share on other sites

@requinix That is the entire action.js file. I didn't write this, it's a sample I got online. It works fine for posting stuff but I can't get a delete to work.
I didn't check with the consol actually. I didn't think of that. I just meant no onscreen errors (I should have clarified that sorry)

Here is a screen shot of the consol error. I blurred out the web address because I'm not allowed to display it in forums (not my rules)

image.png.38118ad838ae670e46ae991b0a7cb421.png

Edited by PNewCode
Link to comment
Share on other sites

@maxxd Thank you. I honestly have no idea why I got that 403 before because I did a lot of messing around with the codes since the post but now I'm still getting a 403 for the image folder, which makes sense because it's for viewing only images from the folder are being displayed correctly on the page. Still I get the id error. The original post's code for sending the delete is still the same

image.png.d820e5665919e43a7dbb9730c1f502ae.png

The error in the console for the id error
image.png.4da9350d37788fabfce70456f2b488d2.png

 

Link to comment
Share on other sites

this javascript was apparently part of a php echo statement at one time, since it is trying to concatenate $row['id'] inside a double-quoted string. you cannot just take something that was in a php context and use it by itself without reading what it is doing and modify it appropriately.

before you can use ajax to make a http request, you must be able to design, write, test, and debug the html and php to accomplish the task. you will need most of the same code and that code must be secure, provide a good user experience, and contain error handling and validation logic so that it will either work or it will tell you why it doesn't, since adding ajax adds a layer on top of everything that makes debugging harder.

next, the point of using a post method form/request when performing an action on the server, is so that a search engine indexing a site won't trigger those actions. the post method form processing code (regardless of using ajax or not) should -

  1. detect if a post method form was submitted before referencing any of the form data
  2. only use $_POST data
  3. enforce user 'delete' permission and data ownership/administrator-ship to control who can delete data
  4. trim, then validate all input data before using it
  5. use a prepared query so that any sql special characters in a value cannot break the sql query syntax, which is how sql injection is accomplished.

to accomplish item #2 on this list, you would use a hidden field in the form for the $row['id'] value. this is the point of the ajax data being set to the form's data - data: $(this).serialize()

Link to comment
Share on other sites

@mac_gyver no it wasn't part of an echo. It was used to pass a form from a different page that didn't require sending an id with it. So now I'm trying to use it for that purpose of using an id. I just don't seem to be able to figure out how. It works fine if there was no php?id= part of anything.

So on the original page, there is a loop that lists the contents from a database. The link that works if it was used to send to the delete-post.php page  is, for one id example, delete-post-2.php?id=2012 (or whatever the id ends up being)

So I decided I wanted the delete to work without leaving the page like what happens when posting something to the database. Thats where I'm stuck because I can't figure out how to pass the id to the delete page with the ajax script

Edited by PNewCode
Link to comment
Share on other sites

@Barand yes even with his post because of the following

 

1 hour ago, mac_gyver said:

this javascript was apparently part of a php echo statement at one time

It wasn't

1 hour ago, mac_gyver said:

only use $_POST data

I thought that I am?
 

1 hour ago, mac_gyver said:

enforce user 'delete' permission and data ownership/administrator-ship to control who can delete data

Yes, I have it so only people with admin permissions can even see the delete button at all. This doesn't help with passing the id though

1 hour ago, mac_gyver said:

to accomplish item #2 on this list, you would use a hidden field in the form for the $row['id'] value. this is the point of the ajax data being set to the form's data - data: $(this).serialize()

I just don't even understand what this means haha. Sadly, this is like if I were to tell someone that has never held a guitar pic, how to play like Seve Vai... @mac_gyver is Steve Vai, I'm the guy holding the pic

1 hour ago, mac_gyver said:

detect if a post method form was submitted before referencing any of the form data

I don't know what that means


Here is what I had, and what I"m trying to do... condensed in a bad drawing because the entirety of the pages is way to much to post in here for one question. It would just be a headache to scroll through

 

forexample.jpg

Link to comment
Share on other sites

I'm beginning to think that ajax isn't the way to go. I like how the original way can send to the database without leaving the page, but I just discovered that you can't send with special characters like an apostrophe like you can if you send the form directly to the php file

Link to comment
Share on other sites

47 minutes ago, Barand said:

Pure bovine ordure

Okay that was put very awesome like lol. I rather liked that. So maybe you can shed some light on that then.

Keep in mind, everything works (except still the delete thing, and I would make this a new question but you commented on my other issue that I made a comment of) but it wont accept special characters to insert into the DB. I can't see any errors because this makes it so you don't leave the page

post_chat.php

<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');

?>
<style>
#hideMe {
    -webkit-animation: cssAnimation 5s forwards; 
    animation: cssAnimation 2s forwards;
}
@keyframes cssAnimation {
    0%   {opacity: 5;}
    20%   {opacity: 4;}
    40%   {opacity: 3;}
    60%   {opacity: 2;}
    80%  {opacity: 1;}
    100% {opacity: 0;}
}
@-webkit-keyframes cssAnimation {
    0%   {opacity: 5;}
    20%   {opacity: 4;}
    40%   {opacity: 3;}
    60%   {opacity: 2;}
    80%  {opacity: 1;}
    100% {opacity: 0;}
}
</style>
<?php

// Start the session

	
	if(!isset($_SESSION['id'])){
    header("location: login.php");
  }

?>


<?php 

	
 $user_id = $_SESSION['id']; 

?>



<?php


error_reporting(E_ALL);
ini_set('display_errors', '1');


$localhost = "localhost";
$dbusername = "deleted for posting";
$dbpassword = "deleted for posting";
$dbname = "deleted for posting";



 #connection string
$conn = mysqli_connect($localhost,$dbusername,$dbpassword,$dbname);

  if(!$conn){
    echo "Database connection error".mysqli_connect_error();
  }


  $sql = "SELECT * FROM users WHERE id = '$user_id'";
  
  

$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
 $user_token =  $row["token"];
 
  $fname =  $row["fname"];

  
  }
} else {
  echo " ";
}




$pname = "";
	 if(!empty($_FILES["file"]["name"])){
     $allowed_img = array('gif', 'png', 'jpg', 'jpeg');

     
      $img_ext = $_FILES["file"]["name"];

           $ext = pathinfo($img_ext, PATHINFO_EXTENSION);
           

           
     if (!in_array($ext, $allowed_img)) {
    
if (!in_array($ext, $allowed_img)) {
    echo '<table width="80%" border="0" cellspacing="0" cellpadding="5" align="center">
  <tr align="center" valign="middle"> 
    <td>
      <p><img src="assetimgs/invalid-banner.png" width="530" height="114"></p>
      <p>&nbsp;</p>
    </td>
  </tr>
  <tr background="assetimgs/fade.png" align="center" valign="middle"> 
    <td> 
      <p><font color="#FFFFFF" face="Verdana, Arial, Helvetica, sans-serif"><b><font size="6">Sorry!</font><br>
        <br>
        Only <font color="#FF9933">gif</font>, <font color="#FF9933">png</font>, 
        <font color="#FF9933">jpeg</font> and <font color="#FF9933">jpg</font> 
        is allowed to upload<br>
        <br>
        No Tokens Have Been Taken<br>
        </b></font></p>
      <p><font face="Verdana, Arial, Helvetica, sans-serif"><a href="picshow/pic-form.php"><font color="#9999FF">Click 
        Here To Try Again</font></a></font></p>
    </td>
  </tr>
</table>';
}


 die();
}


 }

   $mybandid = mysqli_real_escape_string($conn, $_POST['mybandid']);
   $fname = mysqli_real_escape_string($conn, $_POST['fname']);
   $table_pref1 = mysqli_real_escape_string($conn, $_POST['table_pref1']);
   $table_pref2 = mysqli_real_escape_string($conn, $_POST['table_pref2']);
   $name_pref = mysqli_real_escape_string($conn, $_POST['name_pref']);
   $text_pref = mysqli_real_escape_string($conn, $_POST['text_pref']);
   $back_pref = mysqli_real_escape_string($conn, $_POST['back_pref']);
   $message = mysqli_real_escape_string($conn, $_POST['message']);



    if(mysqli_query($conn,$sql)){
     echo " ";
    }
    else{
        echo "Error";
    }

?>





<?php


error_reporting(E_ALL);
ini_set('display_errors', '1');



$connection = mysqli_connect('connection stuff deleted for posting');


extract($_POST);

$data = '';

foreach($_POST as $k => $v) {
    if(empty($data)) {
        $data .= "$k ='$v'";
    } else {
        $data .= ", $k='$v'";
    }
}

$sql = "INSERT INTO livechat_chat set $data";





$results = mysqli_query($connection, $sql);

if($results) {
    echo "<div id='hideMe'>POSTED!</div>";
} else {
    echo "<div id='hideMe'>Changes failed, Please Try Again</div>";
}

And the form.php

<form action="#" method="post" id="manage_post_chat" enctype="multipart/form-data" autocomplete="off" accept-charset="utf-8">
      <font face="Verdana, Arial, Helvetica, sans-serif"><label></label><label><font color="#FF3333"> 
      </font></label> <font face="Verdana, Arial, Helvetica, sans-serif"><font face="Verdana, Arial, Helvetica, sans-serif"> 
      <span class="image-upload"> <label for="file-input"> </label></span></font></font></font> 
      <font face="Verdana, Arial, Helvetica, sans-serif"> 
      <input type="hidden" name="badge" style="font-size:18pt;" value="<?php echo $badge; ?>" required />
      <input type="hidden" name="mybandid" style="font-size:18pt;" value="<?php echo $id; ?>" required />
      <input type="hidden" name="fname" style="font-size:18pt;" value="<?php echo $fname; ?>" required />
      <input type="hidden" name="table_pref1" value="<?php echo $table_pref1; ?>" required />
      <input type="hidden" name="table_pref2" value="<?php echo $table_pref2; ?>" required />
      <input type="hidden" name="name_pref" value="<?php echo $name_pref; ?>" required />
      <input type="hidden" name="text_pref" value="<?php echo $text_pref; ?>" required />
      <input type="hidden" name="back_pref" value="<?php echo $back_pref; ?>" required />
      <input type="hidden" name="back_texture" value="<?php echo $back_texture; ?>" required />
      </font> 
      <table width="100%" border="1" cellspacing="0" cellpadding="2" align="center" class="table-roundmenue8 fixed" bgcolor="#000000" background="brushed01.jpg">
        <tr align="center" valign="middle"> 
          <td colspan="4" height="44"> 
            <table width="98%" border="0" cellspacing="0" cellpadding="1">
              <tr>
                <td width="1%" align="center" valign="middle" class="table-roundmenue-admin" height="4"><span class="image-upload"><label for="file-input"></label> 
                  <font face="Verdana, Arial, Helvetica, sans-serif"><button type="button" class="button-emoji second-btn uk-button uk-button-primary pointer"></button><br>
                  </font> </span> </td>
                <td width="92%" valign="middle" align="center" height="4"> 
                  <input type="text" name="message" size="30" style="font-size:16pt;" class="table-roundmenue-saysomething two uk-textarea uk-margin" placeholder="Say Something" autocomplete="off">
                </td>
                <td width="7%" align="center" valign="middle" height="4"> 
                  <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr align="center" valign="middle"> 
                      <td> 
                        <div class="form-group"> 
                          <input type="submit" class="button btn btn-success" name="submit" value="">
                        </div>
                      </td>
                    </tr>
                  </table>
                </td>
              </tr>
            </table>
            <table width="100%" border="0" cellspacing="10" cellpadding="10" align="right">
              <tr> 
                <td width="8%" background="fade.png" class="table-roundmenue-admin" height="23" align="center" valign="middle"> 
                  <img src="btn/puppy.png" style="font-size:30px;cursor:pointer" onClick="openNav30()"><br>
                  <span class="image-upload"><img src="btn/pic3.png" style="font-size:30px;cursor:pointer" onClick="openNav8()" class="button4 image-upload"></span> 
                </td>
                <td width="8%" background="fade.png" class="table-roundmenue-admin" height="23" align="center" valign="middle"><img src="btn/shot.png" style="font-size:30px;cursor:pointer" onClick="openNav26()"><br>
                  <img src="btn/stickers2.png" style="font-size:30px;cursor:pointer" onClick="openNav29()"> 
                </td>
                <td width="8%" background="fade.png" class="table-roundmenue-admin" height="23" align="center" valign="middle"><img src="btn/requests.png" style="font-size:30px;cursor:pointer" onClick="openNav3()"><br>
                  <img src="btn/requests-free.png" style="font-size:30px;cursor:pointer" onClick="openNav4()"> 
                </td>
                <td width="5%"background="fade.png" class="table-roundmenue-admin" height="23" align="center" valign="middle"><font face="Verdana, Arial, Helvetica, sans-serif" color="#FFFFFF"><b><?php include 'level-tokens.php';?> 
                  </b></font></td>
                <td width="1%" align="right" valign="middle" background="fade.png" class="table-roundmenue-admin" height="23"> 
                  <div id="tableHolder"></div>
                </td>
                <td width="78%" align="right" valign="middle" background="fade.png" class="table-roundmenue-admin" height="23"><span style="font-size:30px;cursor:pointer" onClick="openNav()"><img src="btn/settings.png"></span><br>
<div id="admindiv"></div>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </form>

<script src="action-chatform.js"></script>

And the JS (action-chatform.js)

$(document).ready(function() {
 $('#manage_post_chat').submit(function(e) { e.preventDefault()
 $.ajax({ url: 'post_chat.php', 
 data: $(this).serialize(),
 method: 'POST',
 success: function(resp)
 { $('#error_msg_chat').html(resp); $("#manage_post_chat").trigger("reset");
 }
 })
 })
 }) 

 

Link to comment
Share on other sites

Yes I'll admit I got this wrong because I just bypassed the ajax page and still doesn't work. I'm baffled. I've made several of these pages and not a single issue. I feel like it's something thats staring me in the face to fix and I can't see what it is. I know you just gave me a hint but I don't know what that means haha. Anywho, I think I'll circle back to that issue once I get this bloody delete thing figured out. Argh

Link to comment
Share on other sites

On 8/12/2023 at 6:29 AM, PNewCode said:

Yes, I have it so only people with admin permissions can even see the delete button at all. This doesn't help with passing the id though

Just a quick comment on this.  A user does not need to see a button to call Ajax in order to exploit the Ajax.  All they need is to know that it is there, and they can use whatever technique or tool that they want to, to post to the Ajax url.  

Anything that needs to be secured should have a separate permissions check.  A simple common solution would be to check something stored in the session that indicates someone is an admin, or some other user level.  Then your Ajax code should check that and only execute the actual deletion code when their status is affirmed.

Link to comment
Share on other sites

True @gizmola but for anyone that doesn't have admin permissions get redirected to a page that doesn't have the button on it at all.

@Barand I got the bloody delete button to work. HOWEVER, after all of that work, I discovered that it doesn't work when the entire page is visible through another ajax script that loads the page to the main page (it's a chat window so I use ajax to keep looking for new entries) SO it looks like that all the work was wasted and I can't go this route at all unless I figure out another way to load the page and have it keep looking for database changes. I'm no where near ready to understand node and websockets and stuff

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.