Search code examples
jqueryofbiz

the jquery is not refreshing page


$('.harvest-sch-grade-delete').click(function(){
    jQuery.ajax({
        url: "/smartfarm/control/deleteHarvestSchedule",
        type: "POST",
        data: {harvestScheduleId:$(this).attr("data")},
        success: function(data) {
            jQuery.ajax({
                url: "/smartfarm/control/ajaxHarvestScheduleList",
                type: "POST",
                data: {cropId:$('.harvest-sch-grade-delete').attr("val")},
                success: function(data) {
                    $('.harvest-schedule-list').html(data);
                    $(".alert-box-sch").html("Harvest Grade Schedule Deleted!!");
                    $('.alert-box-sch').show();
                    setTimeout(function() { $(".alert-box-sch").hide(); }, 5000);
                    $('.info-box-sch').hide();
                    $('.warning-box-sch').hide();
                    }
            });
        }
    });
});

my delete function is working for 2 times after that its not deleting?.And i have added one more ftl file for ajaxification.


Solution

  • Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

    As you are updating HTML. You need to use Event Delegation using .on() delegated-events approach.

    i.e.

    $(document).on('event','selector',callback_function)
    

    In place of document you should use closest static container for better performance.

    The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

    For you immediate problem use

    $('.harvest-schedule-list').on('click','.harvest-sch-grade-delete', function(){
        //Your code
    });
    

    instead of

    $('.harvest-sch-grade-delete').click(function(){
        //Your code
    });