0

I have a dynamic table that list some items from my MySQL table, just like this:

   <?php
   $output='';
   $sql1=mysql_query("SELECT * FROM table1 ORDER BY item")or die(mysql_error());
   $sql1n=mysql_num_rows($sql1);
   if($sql1n>=1){
      while($row=mysql_fetch_array($sql1)){
          $item_num=$row['item_num'];
          $item_category=$row['item_category'];
          $item_name=$row['item_name'];

          output .='<tr>';
          output .='<td>'.$item_num.'</td>';
          output .='<td>'.$item_category.'</td>';
          output .='<td>'.$item_name.'</td>';
          output .='<td><a href="#">Delete</a></td>';
          output .='</tr>';
    }else{
          output .='Items not found!";
    }
    ?>

Now I do have my HTML page

    <body>
          <table width="100%"  id="panel" border="0" cellspacing="0" cellpadding="3" class="table2">
         <tr>
            <td>Item #</td>
            <td>Category</td>
            <td>Name</td>
         </tr>
         <?php echo $output; ?>
         </table>
    </body>

I will have the list of Items, Category and Name and an extra column with Delete option if there are some data inside of the database, otherwise, it will return Items Not Found! I would like to click in the Delete link and pass the variables $item_num and $item_category referent to the actual row to a jquery function that will send to the following PHP file, without refresh the actual file, and return a message saying that the item has been deleted successfully!

Delete-Item.php

<?php
    include ('dataconfig.php');

    if((isset($_POST['item_num']))and(isset($_POST['item_category']))){
      $item_num=$_POST['item_num'];
      $item_category=$_POST['item_category'];
      $sql_delete=mysql_query("DELETE FROM table1 WHERE item_num='$item_num' AND item_category='$item_category'")or die(mysql_error());
    }
?>

I don't know the best way to build a jQuery function that is going to do that and I will really appreciate any help that can lead me to finish this task.

Thanks

3
  • Select the elements where the variables are stored, retrieve their text and pass them as parameters in an ajax call. Commented Nov 22, 2012 at 23:00
  • Was about to got into a long answer using jQuery, but noticed you've accepted 0/9 questions. Accept answers by way of thanks to other users - then you may got more attention with future questions Commented Nov 22, 2012 at 23:03
  • <input name="item_category" value="' or 1 = 1 or '" /> unixwiz.net/techtips/sql-injection.html Commented Nov 22, 2012 at 23:20

3 Answers 3

1

You should add $item_num and $item_category to the attributes of tr element.

For example:

output .='<tr id="'.$item_num.'" category="'.$item_category.'">';
output .='<td>'.$item_num.'</td>';
output .='<td>'.$item_category.'</td>';
output .='<td>'.$item_name.'</td>';
output .='<td><a href="#">Delete</a></td>';
output .='</tr>';

in jQuery make event on click on row:

$('table tr[id]').click(function(){
    var obj = $(this);
    $.ajax({
      type: "POST",
      url: 'url/to/Delete-item.php',
      data: { item_num: obj.attr("id"), item_category: obj.attr("category") },
      dataType: "json",
      success: function(data) {
          if (data.success == "true") {
              alert('Item was deleted');
          } else {
              alert('error');
          }
      }
  });
})

and modify Delete-item.php

if((isset($_POST['item_num']))and(isset($_POST['item_category']))){
    $item_num=$_POST['item_num'];
    $item_category=$_POST['item_category'];
    $sql_delete=mysql_query("DELETE FROM table1 WHERE item_num='$item_num' AND item_category='$item_category'")or die(mysql_error());
    $success = ($sql_delete) ? "true" : "false";
    $successArray = array("success" => $success);
    echo json_encode($successArray);
}

I didnt test it.

and dont forget for $item_num use intval and for $item_category mysql_real_escape_string for preventing sql injection.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Alexey! It is working finally! The only thing missing is, after deleted, the item keeps showing in the table, Is there anyway to remove it automatically or before it show up the success message of deleted item?
I just got it! I was mixing your scheme with Tiit's one and it is working! Appreciate you guys! Thank you.
Alexey, if I put the price for each item and the price total in the bottom of the table,is there anyway to dynamiclly update this total when the Delete action is applied?
You can make a javascript variable in window scope for total amount and in success callback of jQuery's ajax method (before of removing deleting element) add smthg like that: totalAmount -= parseFloat($("#" + item_id + " td#amount").val()); $("#totalAmountTD").val(totalAmount); //totalAmountTD is an id for column of total amount.
instead of " td#amount" better use " td.amount" for identifying of column of amount of item.
0

I would add ID's to your table, i.e. like this:

output .='<tr id="'.$item_num.'">';

in the back-end where You do the deletion (delete_item.php) I'd add some output to verify the successful deletion:

$sql_delete=mysql_query("DELETE FROM table1 WHERE item_num='$item_num' AND item_category='$item_category'")or die("0");
if ($sql_delete) {
   print $item_num;
}

and when calling a delete then use jQuery library:

function delete_item(item_id, cat_id) {
  $.post('delete-item.php', { 
    // POST parameters
    item_num: item_id, 
    item_category: cat_id 
  }, function(data) {
     // if returned data is the deleted item id then.. 
     if (data==item_id) {
        // .. remove the row from the table.
        $("#" + item_id).remove();
     }
  });
}

1 Comment

For some reason, it doesn't work! I am sorry. How do I know if the JQuery function is catching the id's that I just created if you didn't mention any # in the function?
0

Give your tr's or td's ids (or class names if that would be better).

$output .= "<tr id='row_{$item_num}'>";
$output .= "<td class='item_category'>{$item_category}</td>";
...
$output .= "<td><a href='#' class='delete' rel='{$item_num}'>Delete</a></td>";
...

Grab that value like this: (note, you could also use .siblings() or .parent() to get the row and item_cat td. Either way...

$('a.delete').live('click', function(e) {
  e.preventDefault();
  var item_num = $(this).attr('rel');
  var this_row = $('tr#row_'+item_num);
  //Now you have the parent row. You can do anything you want with it. If you just want to get the value of the corresponding item_cat, you could then do
  var item_cat = $(this_row).children('td.item-category').text();
  $.post('/your_url', { item_number: item_num, item_category: item_cat }, function(data) {
      //deal with the return result of 'data'
  });
});

4 Comments

How do I get the "the_id_you_assigned" if it is dynamic?
instead of just echo "<tr>";, do something like echo "<tr id='row_{$item_num}'>"; I often give my anchor a class, like 'delete', then assign it an rel='item_num'. So when the link is clicked, grab the rel var rel = $(this).attr('rel'); Now use that to formulate the tr id. var my_value = $('tr#row_'+rel).text();
I couldn't understand when you say "anchor a class like delete" Can you example that?
$output .= "<td><a href='#' class='delete' rel='{$item_num}'></a></td>";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.