E-g
E-g

Reputation: 544

Getting javascript to work after loading content via Ajax (Wordpress)

I'm having some problems with loading content via Ajax. I can't get the Woocommerce javascript to work when I am loading a product via Ajax.

The content is loaded like this:

App.js

$.post( settings.ajaxurl, data, function( response ) {
        $button.prop("disabled",false);
        if(true === response.success) {
            $('.sidebar').html(response.data);
        }  else {
            $contentWrapper.find('.response').html(response.data.general).show();
        }
    } );

And the backend returns a template part when the request was successful.

Ajax.php

ob_start();
    if( get_user_meta( $user->ID, 'my_custom_field', true ) == 1 ) {
        get_template_part( 'template-parts/book' );
    } else {
        get_template_part( 'template-parts/additional-information' );
    }
    $response = ob_get_clean();
    wp_send_json_success( $response );

Inside the template part "book" is a single bookable product (via Woocommerce Bookings) which requires some javascript to work for selecting time/date etc. When this template part is loaded via Ajax the javascript is not working, and I can therefore not book the product.

However if I refresh the page, the bookable product will be loaded instantly without Ajax, and now everything works perfectly.

The javascript is included globally in the header of the page and is always present. But when the new content is loaded via Ajax, I guess I need to manually fire any document.ready functions that is needed for the booking form to work.

I just cant wrap my head around how I should do this, so any help is very appreciated.

Upvotes: 1

Views: 529

Answers (1)

Roman Panevnyk
Roman Panevnyk

Reputation: 313

I guess you should use your jquery events dynamically because you DOM was changed.

Try to use:

$(document).on( eventName, selector, function(){} );

instead of:

$(selector).on( eventName, function(){} );

and etc...

Upvotes: 0

Related Questions