I want to delete items from firebase database using javascript on button click

Viewed 66

You can see the image which item i want to deleteenter image description here

enter image description here

The code of fetch is give below

var dbImages = firebase.database().ref("images");

  dbImages.on("value", function(images){

    if(images.exists()){
        var categorieshtml = ""; 
        images.forEach(function(image){

            console.log(image.val().title);
            
            categorieshtml += "<tr>";

            //for category name
            categorieshtml += "<td>";
            categorieshtml += image.key;
            categorieshtml += "</td>";

            //for category description
            categorieshtml += "<td>";
            categorieshtml += image.val().title;
            categorieshtml += "</td>";

             categorieshtml += "<td>";
            categorieshtml += image.val().desc;
            categorieshtml += "</td>";
            
            //for category thumbnail
            categorieshtml += "<td> <img width='250' height='150' src='";
            categorieshtml += image.val().url;
            categorieshtml += "' /></td>";

        
            categorieshtml += "<td>";
            categorieshtml += "<button id='btn-delete' onclick='delete_row("+image.key+")'>Remove</button>"
            categorieshtml += "</td>";

            
            categorieshtml += "</tr>";


        });

        $("#images").html(categorieshtml);
    }

});




function delete_row(childKey) { 



 firebase.database().ref().child('images/' + childKey + '/').remove();

  alert('row was removed');
  reload_page();
}

I want to delete node which given in image using button. I can easily fetch the value but the delete button is not working please help guys. I want to delete the item from the Firebase real-time database by clicking the button in JavaScript.

1 Answers

You're missing quotes around the argument in the call to delete_row here:

categorieshtml += "<button id='btn-delete' onclick='delete_row("+image.key+")'>Remove</button>"

If you check the generated HTML, you'll see that it looks like this:

delete_row(-N2j...JIWFH)

The argument here is interpreted as a token/variable, instead of as a literal string value.

To fix this, add yet another pair of quotes in your code:

categorieshtml += "<button id='btn-delete' onclick='delete_row(\'"+image.key+"\')'>Remove</button>"
Related