'Return html wrapped template part Ajax call Wordpress

I've built a custom post filter in Wordpress using Ajax.

function filterPublications(filters, filterType) {
  filters = JSON.stringify(filters);
  $.ajax({
    type: 'POST',
    url: window.sage.ajax_url,
    dataType: 'html',
    data: {
      action: 'ajax_filter',
      publish: 'past',
      filters,
      posts_per_page: 3,
      filter_type: filterType,
    },
    success: response => {
      $('#publications').html( response );
    },
  })
}

And in functions.php I make a post query to query on the filtered values. What I would like is to return a template part wrapped in html for jQuery to fill the html. But I'm not sure how.

I've tried:

$response = '';
if ( $filtered_posts->have_posts() ) {
  while ( $filtered_posts->have_posts() ) {
    $filtered_posts->the_post();
    $response .= '<div class="col-md-4">' . get_template_part('partials/blocks/publications') . '</div>';
  }
}

echo $response;

and

$response = '';
 if ( $filtered_posts->have_posts() ) {
   while ( $filtered_posts->have_posts() ) {
     $filtered_posts->the_post();
     $response .= '<div class="col-md-4">';
     ob_start();
     get_template_part('partials/blocks/publication');
     $response .= ob_get_contents();
     ob_end_clean();
     $response .= '</div>';
   }
}

echo $response;

Both are not returning the expected response, which is the template part wrapped in the bootstrap column div. How would I do this?



Solution 1:[1]

I suggest you to try following peace of code

ob_start();
if ( $filtered_posts->have_posts() ) {
    while ( $filtered_posts->have_posts() ) {
        $filtered_posts->the_post();
        echo '<div class="col-md-4">';
            get_template_part('partials/blocks/publication');
        echo '</div>';
    }
}
$response = ob_get_clean();

echo $response;

Please check and let me if it work for you or not.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shebaz