简体   繁体   中英

Adding or deleting table rows with MySQL, jQuery and Ajax

I have a script that removes row from table with MySQL and jQuery. Now I need to insert rows too. How should I modify the code?

index.php

if (mysql_num_rows($result2) > 0) {
    echo "<table>";
    while ($searchIds = mysql_fetch_array($result2)) {
        echo "<tr class='show'>
                  <td>".$searchIds["channel_name"]."</td>
                  <td>".$searchIds["customer_id"]."</td>
                  <td>
                      <a class='delete' href='#' id='".$searchIds['id']."' channel_id='".$searchIds["channel_name"]." ".$searchIds["customer_id"]."'>Delete id</a>
                  </td>
              </tr>
          </table>";
    }
    echo "</table>";
}

.js

$(function() {
    $(".delete").click(function(){
        var element = $(this);
        var del_id = element.attr("id");
        var info = 'deleteid=' + del_id;
        var channel_id = element.attr("channel_id");
        if(confirm("Delete?\n\n" + channel_id)){
            $.ajax({
                type    : "POST",
                url     : "scripts/delete.php",
                data    : info,
                success : function(){}
            });
            $(this).parents(".show")
                .animate({ backgroundColor: "#003" }, "slow")
                .animate({ opacity: "hide" }, "slow");
        }
        return false;
    });
});

And delete.php has simple query for deleting row.

You can try this:

index.php

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
</table>

js file

$(function() {
    $(".delete").click(function(){
                .........
    });
    $(".add").click(function(){
        var element = $(this);
        $.ajax({
          type    : "POST",
          url     : "scripts/add.php",
          data    : { add your variables } 
          success : function(){}
               $('#myTable > tbody:last').append('<tr><td>...</td><td>...</td><td>...</td></tr>');
          });
        return false;
    });
});

In your file add.php you can return a json array and read it to the new row .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM