2

I'm loading php output into a div using ajax on a page(jobs.php), this output is refreshed every few seconds to show an up to date list of records from sql.

I am trying to use ajax to delete a chosen record, this works fine on a stand alone page however when I try and do it from the jobs.php page nothing happens.

$(function () {
    $('.trash').click(function () {
        var del_id = $(this).attr('id');
        var $ele = $(this).parent().parent();

        $.ajax({
            type: 'POST',
            url: 'deleterecord.php',
            data: {del_id: del_id},
            success: function (data) {
                if (data == "YES") {
                    $ele.fadeOut().remove();
                } else {
                    alert("record could not be deleted")
                }
            }
        });
    });
});

deleterecord.php

$delid = $_POST['del_id'];

$query5 = "DELETE from Records WHERE id = '$delid'";
$sql5 = mysqli_query($connection, $query5) or die(mysqli_connect_error());

if(isset($sql5)) {
    echo "YES";
} else {
    echo "NO";
}

jobs.php

<script type="text/javascript">
    refreshdiv();
</script>

any suggestions on where I could be going wrong??

function refreshdiv() {

    // The XMLHttpRequest object

    var xmlHttp;
    try {
        xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
    } catch (e) {
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("Your browser does not support AJAX.");
                return false;
            }
        }
    }
}
IlGala
  • 3,331
  • 4
  • 35
  • 49
dev7
  • 183
  • 2
  • 15

1 Answers1

5

Since the delete buttons are loaded dynamically you need to use delegated events.
So we need to bind the click event to a parent element that exists at load time,
ex body.

Replace this

$('.trash').click(function () {

With this

$('body').on('click','.trash',function(){
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42