1

So I've made an AJAX request, it submits fine and returns the HTML on success as expected - but in the HTML that is returned to the target div element, it has a button. I've added jQuery to this, that when it's clicked, it is to hide the HTML from the AJAX success.

In short: I want the close button to close the div, but it doesn't seem to be working.

$('#user_report__dd #make_report').click(function(){
        var interaction_type = $(this).data('interaction_type');
        var user_id = $(this).data('user_id');
        $.ajax({
            type: 'POST',
            dataType: 'html',
            url: ajax_url,
            data: {
                interaction_type: interaction_type,
                user_id: user_id,
            },
            success:function(html){
                // $('.ajax_call').html(html);
                $('.ajax_call').html(html);
                // stop body from scrolling
            }
        });
    });
if(isset($_POST['interaction_type']) && $_POST['interaction_type'] == 'report_user'){
    global $report;
    $report->Form($_POST['user_id'], 'user');
    // This returns the HTML
}

And then in my main jQuery file

$('.close').click(function(){
        $(this).parents('.pulled_in_html');
    });
  • 2
    To point you in the right direction, just like @matt did, use the "on" for your event listener. When you use the `click` event listener you attach it to an existing element, so when you javascript loads, you're trying to attach the event listener to an element that doesn't yet exist, while his `$('body').on('click', '.close', ...)` will attach the event listener to the existing body element and listen for all clicks within the body element and trigger for any child elements with the class "close". – Jonathan Nielsen Mar 29 '19 at 10:27
  • Understood. So how would you tackle this? –  Mar 29 '19 at 11:07

1 Answers1

5

Because the element doesn't exist in the DOM when your click event handler is created, it doesn't find the element. Instead you can delegate the event from body like below:

$('body').on('click', '.close', function(){
    $(this).parents('.pulled_in_html');
});

Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. That event listener analyzes bubbled events to find a match on child elements.

You can read more about event delegation here

Your code doesn't seem to be making any attempt at hiding anything and I don't know if you left this out on purpose or not, but to hide the element, you can chain the hide() method onto this line:

    $(this).parents('.pulled_in_html').hide();
Marty
  • 144
  • 11
Matt
  • 1,455
  • 4
  • 11
  • 27