douyouqian8550
2016-06-08 04:46
浏览 69

嵌套在AJAX输出中的jQuery AJAX函数(innerHTML)

I use jQuery Ajax (innerHTML) to generate a listing of records from MySQL database. I would like to put a DELETE button next to each of these records.

Once you press the DELETE button, the record will be removed from database and faded away from the displayed list. Is it possible to do it - to nest another jQuery Ajax function in innerHTML output?

Please note that the DELETE function I use works perfectly fine with standard PHP/HTML output.

In the main php file (test1.php ) I have form to choose a time frame and once form is being submitted function bellow is generating my output in the same file:

<div id="display_taxation_data"></div>

Code responsible for generating listing:

function showDataLabour(str) {
if (str == "") {
    document.getElementById("display_taxation_data").innerHTML = "<h3>No results. Please select taxation period.</h3><hr>";
    return;
} else {
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("display_taxation_data").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("GET","accounting_get_period_data_labour.php?period="+str,true);
    xmlhttp.send();
    }
}

Code for accounting_get_period_data_labour.php ( set of records being generated based on previously selected time frame.)

echo "<tr id='record-$id'>";
echo "<td width='40'><a href='accounting_expenses_delete.php?delete=$id' class='delete'><i class='fa fa-times fa-2x' aria-hidden='true' title='Delete'></i></a></td>";
echo '</tr>';

And delete function that I want to trigger once button DELETE is pressed:

$(function() {
$('a.delete').click(function(e) {
    e.preventDefault();
    var parent = $(this).parent("td").parent("tr");
    console.log('idno : ' + parent);
    $.ajax({
        type: 'post',
        url: 'accounting_expenses_delete.php',
        data: 'delete=' + parent.attr('id').replace('record-',''),
        beforeSend: function() {
            parent.animate({'backgroundColor':'#fb6c6c'},100);
        },
        success: function() {
            parent.fadeOut(100,function() {
                parent.remove();
            });
        }
    });
});
});

And finally short code for accounting_expenses_delete.php

<?
include "connectdb_mysqli.php"; 
$testdel = $_POST['delete'];
$result = $mysqli->query("DELETE FROM `test` WHERE id='$testdel'"); 
 ?>

Please let me know if you need some more information.

Looking forward to your advice or solution on how I can achieve that DELETE action. Thank you

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • douleijiang8111 2016-06-08 05:16
    已采纳

    We can add a data-id tag for each of the link to delete:

    echo '<td width="40">
              <a href="#" data-id="'.$id.'" class="delete"><i class="fa fa-times fa-2x" aria-hidden="true" title="Delete"></i></a>
          </td>';
    

    Once this button has been clicked, it will run an Ajax request:

    $(document).on('click', '.delete', function(e) {
    
        e.preventDefault();
    
        var elem = $(this),
            id = elem.attr('data-id'); /* GET THE ID NO. OF THE CLICKED DELETE LINK */
    
        $.ajax({ /* AJAX REQUEST */
            type: 'post',
            url: 'accounting_expenses_delete.php',
            data: {'delete-id': id},
            success: function() {
                elem.closest('tr').hide(200);
            }
        });
        return false;
    });
    

    Then for your accounting_expenses_delete.php:

    include('connectdb_mysqli.php');
    
    $stmt = $mysqli->prepare("DELETE FROM test WHERE id = ?");
    $stmt->bind_param("i", $_POST["delete-id"]);
    $stmt->execute();
    $stmt->close();
    

    I used prepared statement to do the DELETE query above.


    Note:

    jQuery is a javascript library and the script I had provided is a jQuery, so it means you have to include first the jQuery library before your script.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
    <script>
        /* YOUR JQUERY SCRIPT HERE */
    </script>
    
    已采纳该答案
    打赏 评论
  • dongsi5381 2016-06-08 04:52

    Are you passing the value from PHP to JavaScript? If so, You may have some luck with eval() which can execute a code block that is stored in a string.

    打赏 评论
  • dse3168 2016-06-08 05:27

    You used raw Javascript for your first AJAX call to get the listings. And suddenly, you are changing to JQuery for your deletion. Why not either do both in Pure Javascript or JQuery? I think JQuery is a little more easier. Below is a JQuery-based solution for fetching and deleting data:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
        <script type="text/javascript">
            (function ($) {
                $(document).ready(function (e) {
    
                    function showDataLabour(str) {
                        var taxDataBlock   = $("#display_taxation_data");
    
                        if(str == ""){
                            taxDataBlock.html("<h3>No results. Please select taxation period.</h3><hr>");
                        }else{
                            $.ajax({
                                type    : 'GET',
                                url     : 'accounting_get_period_data_labour.php?period=' + str,
                                success : function(data) {
                                    if(data){
                                        taxDataBlock.html(data);
                                        var generatedData   = $(data);
                                        var deleteBtn       = generatedData.find("a.delete");
                                        // SINCE THE LISTINGS ARE GENERATED HERE,
                                        // TARGET < a class='delete'> ELEMENT(S) WITHIN THE GENERATED CONTENT
                                        // AND PASS IT AS AN ARGUMENT TO THE DELETE FUNCTION...
                                        deleteViaAjax(deleteBtn);
                                    }
                                }
                            });
                        }
                    }
    
                    function deleteViaAjax(deleteBtn){
                        deleteBtn.click(function(e) {
                            e.preventDefault();
                            var parent = $(this).parent("td").parent("tr");
                            console.log('idno : ' + parent);
    
                            $.ajax({
                                type: 'post',
                                url : 'accounting_expenses_delete.php',
                                data: {'delete': parent.attr('id').replace('record-','')},
                                beforeSend: function() {
                                    parent.animate({'backgroundColor':'#fb6c6c'},100);
                                },
                                success: function() {
                                    parent.fadeOut(100,function() {
                                        parent.remove();
                                    });
                                }
                            });
                        });
                    }
                });
            })(jQuery);
    
        </script>
    
    打赏 评论
  • dongshan9338 2016-06-08 06:15

    Your delete() function use jQuery to make an ajax call. Why your showDataLabour() function use native XMLHttpRequest? It's better to use jQuery too :-)

    You can not use:

    $(function() {
        $('a.delete').click(function(e) {
            // your code for delete action
        });
    });
    

    to bind click event to your delete button, because the button does not exist when the page has been loaded completely. It will be exist AFTER an ajax call made by showDataLabour() function has been completed.

    In this situation, you can use delegated event. Try this:

    $(function() {
        $('body').on('click', 'a.delete', function(e) {
            // your code for delete action
        });
    });
    

    Read http://api.jquery.com/on/ for further information.

    打赏 评论
  • douwudie8060 2016-06-09 06:09
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script>
    function showDataExpenses(str) {
    if (str == "") {
        document.getElementById("display_taxation_data").innerHTML = "<h3>No results. Please select taxation period.</h3><hr>";
        return;
    } else {
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("display_taxation_data").innerHTML = xmlhttp.responseText;
            }
        };
         xmlhttp.open("GET","accounting_get_period_data_expenses.php?period="+str,true);
        xmlhttp.send();
    }
    }
    
    $(document).on('click', '.delete', function(e) {
    e.preventDefault();
    var elem = $(this),
        id = elem.attr('data-id'); /* GET THE ID NO. OF THE CLICKED DELETE LINK */
        $.ajax({ /* AJAX REQUEST */
        type: 'post',
        url: 'accounting_expenses_delete.php',
        data: {'delete-id': id},
        success: function() {
            elem.closest('tr').hide(200);
        }
    });
    return false;
    });
    </script>
    
    打赏 评论

相关推荐 更多相似问题