Maria Muresan
Maria Muresan

Reputation: 93

Onclick event doesn't work after AJAX in JQuery issue

This is the Jquery code:

$("#save").on ('click', function(){  // save new person
    var new_name = $("#name").val();
    var new_age = $("#age").val();

    var formData = { name : new_name, age : new_age }; 

    $.ajax({
        url : "ajax.php",
        type: "POST",
        data : formData,
        success: function(data, textStatus, jqXHR){
            get_old_html = $("#result_json").html(); // getting current html data
            var array = JSON.parse(data);  // getting the JSON
            var html = "";
            for (var i = 0 ; i < array.length; i++){
                var split = array[i].split("||");
                html = html + "<tr><td>"+ split[1] +"</td><td>"+ split[2]  +"</td><td><center><a href ='#' class ='delete_person' id ='"+ split[0] +"'>X</a></center></td></tr>"; // create the new html with the new item
            }
            $("#result_json").html(html + get_old_html); // add the new html and the content of it

            $("#add_new_person").hide();
            $("#add_person").show(); 
                //mesaj de confirmare
        },
        error: function (jqXHR, textStatus, errorThrown){
            console.log(errorThrown);
        }
    });
});

$(".delete_person").on('click',function(){  //delete person
    id = $(this).attr("id");
    var formData = { id : id };
    $.ajax({
        url : "ajax.php",
        type: "POST",
        data : formData,
        success: function(data, textStatus, jqXHR){
            var remove = JSON.parse(data);  // getting the JSON
            if (remove == "success"){
                $("#"+id).closest("tr").remove();
            }
        },
        error: function (jqXHR, textStatus, errorThrown){
            console.log(errorThrown);
        }
    });
});

The fact is then when i save a new person and after that I want to delete that person, the onclick event on the class "delete_person" does not work. But when I refreshed the page it works. What should I do ? and all of it is included in $( document ).ready(function() { });

Upvotes: 0

Views: 2904

Answers (4)

Vatsal
Vatsal

Reputation: 2128

It is because the element doesn't exist in the document. You need to use

$(document).on("click", "selector", function(){do something});

Hope this helps :)

Happy Learning :)

Upvotes: 0

noobHere
noobHere

Reputation: 251

i think you should just add a native javascript function like this

for (var i = 0 ; i < array.length; i++){
                var split = array[i].split("||");
                html = html + "<td><a href='#' onlick='deletePerson("+split[1]+")'>Delete</a></td>" // create the new html with the new item
            }

then outsude your $(document)

function deletePerson(id){
    var person_id = id  ;
    //ajax code here
 }

this is what I do whenever i have a dynamic table that has a remove function using jquery

Upvotes: 0

Terry
Terry

Reputation: 66103

.delete-person is an element that is dynamically added to the DOM after the AJAX call has been made. Since your jQuery script runs upon DOMready (when .delete-person is not present during runtime), the click event would not be bound to the element.

The line $('.delete-person').on('click', function() { ... }); is functionally identical to $('.delete-person').click(function() { ... });. The gist is that you are attaching the click event handler to the element .delete-person, which is not present in the DOM at runtime.

Instead, listen to the click event originating from .delete-person that is bubbling up to the document object instead:

$(document).on('click', '.delete-person', function() {
    // Do stuff here to delete person
});

What the above code does differently is that you are listening for the click even on the document object, but verifying that the click event originated from a child element that has a class of .delete-person. Since the click event will always bubble to the document regardless of whether the object is present or absent during runtime, you will be able to delete the person this way ;)

Upvotes: 7

Ammar
Ammar

Reputation: 719

make sure about response data and use

$(this).closest("tr").remove(); 

or try:

$(".delete_person").on('click',function(){ 
    var element = $(this);

then

$(element).closest("tr").remove(); 

Upvotes: 0

Related Questions