Solved

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

Posted on 2015-02-03
20
127 Views
Last Modified: 2015-02-14
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 :
SampleFollowing 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

0
Comment
Question by:Suneet Pant
  • 9
  • 6
  • 3
  • +1
20 Comments
 
LVL 8

Expert Comment

by:Ahmed Merghani
ID: 40588050
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.
0
 

Author Comment

by:Suneet Pant
ID: 40588309
i have checked that but the same problem is coming again. data is not deleting from the table. Pls help
0
 
LVL 8

Expert Comment

by:Ahmed Merghani
ID: 40588343
Did you log the "query" variable to ensure it's passed properly?
0
 

Author Comment

by:Suneet Pant
ID: 40588348
No. I actually don't know how to do that.
0
 

Author Comment

by:Suneet Pant
ID: 40588361
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.
0
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 40588482
Your ajax is not selecting the ID. This line here:

var id =  $("td:nth-child(1)", this).text();

Open in new window


Is trying to get the 1st TD within 'this', which is actually the <a> tag. Try this and see how you get on:

var currentRow = $(this).parents('tr');
var id =  $("td:nth-child(1)", currentRow).text();

Open in new window

0
 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 500 total points
ID: 40588483
Also, later in your code, you can use the currentRow variable to fade out:

currentRow.fadeOut('slow', function() {$(this).remove();});

Open in new window

0
 

Author Comment

by:Suneet Pant
ID: 40588597
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.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40588669
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 :)
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 33

Expert Comment

by:Slick812
ID: 40589703
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.
0
 

Author Comment

by:Suneet Pant
ID: 40590441
Hi Chris, I am here again. I have an Update Button over the top of the pic shown below :
PicNow 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
0
 

Author Comment

by:Suneet Pant
ID: 40590460
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.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40590687
Hey Suneet,

No worries - I've unaccepted the answer so you can go ahead and re-accept it :)
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40590690
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.
0
 

Author Comment

by:Suneet Pant
ID: 40590860
Hi Chris. Thanks. Here is the link :
0
 

Author Comment

by:Suneet Pant
ID: 40590861
Sorry the link is here :
Link
0
 

Author Comment

by:Suneet Pant
ID: 40597983
I've requested that this question be deleted for the following reason:

My Subscription has ended so I removing my question
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40597984
The question was answered in full, so the OP should accept it - not delete the question!!
0
 
LVL 8

Expert Comment

by:Ahmed Merghani
ID: 40598088
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.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
These days socially coordinated efforts have turned into a critical requirement for enterprises.
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now