Link to home
Start Free TrialLog in
Avatar of Suneet Pant
Suneet PantFlag for India

asked on

How to delete records on clicking an image in different rows in html table using ajax

Hello there,

I am trying to delete a record based on the delete image at the end of each row in html5 table. I am just a beginner in ajax jQuery.  I think there is something wrong in the jquery part. The record is not deleting from the database, although on clicking the  "x" rounded button, it shows that the record is deleted Please Help
I am sending an image that will help you in solving and understanding my problem :
User generated imageFollowing is my code :
1. cart.php
<?php session_start(); ?>
<?php
include ("dbcon.php");
include("BrowserDetection.php"); 
include("included_functions.php"); 
?>
<!DOCTYPE html>
<html>
  <head>
  <title></title>
  <script type="text/javascript" src="js/modernizr.js"></script>
  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
  <script type="text/javascript" src="js/fabric.js"></script>
  <link rel="stylesheet" type="text/css" href="css/dsgncnv.css">
  <script type="text/javascript">
    $("table#display td a.delete").click(function()	{
     if (confirm("Are you sure you want to delete this row?"))
     {
	var id =  $("td:nth-child(1)", this).text();
	var data = 'id=' + id ;
	var parent = $(this).parent().parent();
	$.ajax(
	{
	   type: "POST",
	   url: "delrow.php",
	   data: data,
	   cache: false,
	   success: function()
	   {
	     parent.fadeOut('slow', function() {$(this).remove();});
	   }
	});				
     }
    });
    $('table#display tr:odd').css('background',' #FFFFFF');
   });
  </script>
  </head>
<body>
  <div class="hdr-txt">
   <span class="spnid">SHOPPING CART</span>
  </div>
  <hr style="float:left; margin-left:5%; width:90%; height:1px; background-color:#D7D5D5; margin-bottom:10px" />

  <div class="disp_recs">
    <?php
        $var = trim($_SESSION['rahul@xys.com']);
	$query = "SELECT user_id FROM user_dtls where u_emailid = '{$var}'";
	$retrv = mysqli_query($connection, $query);
	$retrvarr = mysqli_fetch_array($retrv);
	if (!$retrvarr)
	{ die("Database Query failed." . mysqli_error($connection)); }
	else {$getid = $retrvarr[0];}

	//get details based on id
	$pickrecs = "SELECT t_ordid, DATE_FORMAT(tord_dt,'%d-%m-%Y') as label_date, file_path, file_name FROM utmp_orders where user_id = '{$getid}'";
	$result = mysqli_query($connection, $pickrecs); ?>
        <table id='display'>
          <thead>
	    <tr>
		<th>Labels</th>
		<th>Creation&nbsp;Date</th>
		<th>Total&nbsp;Price (&nbsp;&pound;&nbsp;)</th>
		<th></th>
            </tr>
	  </thead>
	  <?php while($resultarr = mysqli_fetch_assoc($result)){ ?>
	  <tbody>
	    <tr>
		<!--<td style="display:none;"><?php //echo $resultarr["t_ordid"] ?></td>-->
		<td><?php echo $resultarr["t_ordid"] ?></td>
		<td><?php echo $resultarr["label_date"] ?></td>
		<td><?php
		$pickrecs = "SELECT rt_qty, rt_cost FROM rate_mast order by rt_qty";
		$rtlist = mysqli_query($connection, $pickrecs); 
		echo "<select name='ratelist' value='' class='rdd'>";
		while($rtlistarr = mysqli_fetch_assoc($rtlist)){ 
		  echo "<option value = $rtlistarr[rt_qty] data-cost='" . $rtlistarr[rt_cost] . "'>$rtlistarr[rt_qty]</option>";
		}
		echo "</select>";
		?></td>
		<td><input type="text" name="i-cost" value="5.95" readonly class="icost"></td>
		<td><a href="#" class="delete" style="color:#FF0000;"><img src="images\cartidel.jpg" alt="" style="width:24px; height:24px"</a></td>					
	    </tr>
            <?php } ?>
         </table>
	 <?php 
	   mysqli_free_result($retrv);
	   mysqli_free_result($result);
	 ?>
      </div>
   </body>
</html>
<?php
	mysqli_close($connection);
?>

Open in new window


2. delrow.php
<?php session_start(); ?>
<?php
  include ("dbcon.php");
  if(isset($_REQUEST["id"])) 
  {
    $varid=$_REQUEST["id"];
    $query="delete * from utmp_orders where t_ordid ='{$varid}'";
    $result = mysqli_query($connection, $query); 
    if (!$result)
    { die("Database Query failed." . mysqli_error($connection)); }
    } else {
      echo '0';
    }
    exit;
?>
<?php
   mysqli_free_result($result);
   mysqli_close($connection);
?>

Open in new window

Avatar of Ahmed Merghani
Ahmed Merghani
Flag of Sudan image

I realized that in your delrow.php file your query is:
$query="delete * from utmp_orders where t_ordid ='{$varid}'";

Open in new window

I think it must be:
$query="delete * from utmp_orders where t_ordid =$varid";

Open in new window


Without the brackets and the single quotations.

Also insure that your AJax call pass the id correctly by log the $query variable.
Avatar of Suneet Pant

ASKER

i have checked that but the same problem is coming again. data is not deleting from the table. Pls help
Did you log the "query" variable to ensure it's passed properly?
No. I actually don't know how to do that.
I tried to check using var_dump  :  echo var_dump($_REQUEST['id']); but nothing happened.

Also please see whether - var id =  $("td:nth-child(1)", this).text(); - is the correct syntax to get data from the hidden column.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Chris. Thanks a million. I seriously now have started wondering how will you feel if I will ask for more help later on in the future.
Thank you very much for your timely help.
Hey Suneet.

No worries asking for more help. That's what we're here for. I don't always see new questions asked, so you can always comment on one I've already responded to and I'll get notified - just link to your new question and I should be able to take a look.

Don't forget to accept an answer and close off questions when you're done. Helps keep EE nice and clean :)
greetings Suneet Pant, , as you are finding out, there is much more to using the javascript browser AJAX than you might think. You may should take some time to look at some ajax turorials to see some things that ARE NECESSARY to have a viable AJAX html page?

I will try and give you some suggestion about your PHP code in the  delrow.php  , your server side AJAX response.
Please consider, you CAN NOT use your OLD PHP web page thinking for an AJAX response page. You do NOT send back a full web page as you normally do in PHP.

you use this -
    if (!$result)
        { die("Database Query failed." . mysqli_error($connection)); }

you need to know that the AJAX receptor function you coded -
     success: function()
         {
           parent.fadeOut('slow', function() {$(this).remove();});
         }
Does not in any way check what the  delrow.php  sends back, so any success or failure of Database, or PHP page error will go unnoticed by this AJAX, this is incorrect AJAX programming, you need to at least be able to use-check the send back from delrow.php .

Your SQL syntax is not correct, a DELETE needs to be in this format -
     "DELETE FROM utmp_orders WHERE t_ordid=3"

It is vastly important to prevent SQL injection, so you MUST escape the  $varid  before you use it in a SQL string.

also, in your javascript, you are trying to "fish out" a ROW id value by getting the ROW and popping out the first <td> innerHTML, I find it easier and more efficient to add a "data-id" attribute to the <a> that is clicked, then you can just use the jquery   .data('id') on the this to get an ID to send up to AJAX server.
Hi Chris, I am here again. I have an Update Button over the top of the pic shown below :
User generated imageNow please this time help me with the code as things are not coming in my mind how to do it. Lets say database table name is "cart", I want to update the contents of each row of the html table (as shown in the picture) to be saved in the "cart" table in one go using jquery and ajax. Rest of the code is same as above. Please help
Hi Chris, Sorry you solved my problem but by mistake I have given points to "Ahmed Merghani". This guy is of no help at all.
Hey Suneet,

No worries - I've unaccepted the answer so you can go ahead and re-accept it :)
Don't quite understand your question about the update - the image doesn't show an update button. If you want to ask this as a new question, and just post a link to it here, I'll try and take a look.
Hi Chris. Thanks. Here is the link :
Sorry the link is here :
Link
I've requested that this question be deleted for the following reason:

My Subscription has ended so I removing my question
The question was answered in full, so the OP should accept it - not delete the question!!
I think the thing that should be deleted is this kind of user like "Suneet Pant" who are manipulated!
There is no reason to delete this question at all. If the points will not be splitted as he mentioned
Hi Chris, Sorry you solved my problem but by mistake I have given points to "Ahmed Merghani". This guy is of no help at all.
at least "Chris Stanyon" must have all the points as he mentioned.