Roots Discourse

Adding template partial to AJAX output

Hi,

I’m new to Sage so excuse any ignorance and poor practices on my part.

I’m currently testing a custom post type list with AJAX filtering. I can get the query correctly and output data for each post however I’m now at a stage where I want to use a blade partial for each post.

I have seen a few others ask this question but I can;t seem to get it working in my own context. Here’s my current function, the $responsenear the bottom is what is output -

add_action('wp_ajax_get_ajax_posts',  __NAMESPACE__ . '\\get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts',  __NAMESPACE__ . '\\get_ajax_posts');

function get_ajax_posts() {
    // Query Arguments
    if(isset( $_POST['categoryfilter'] ) ) {
      $args = array(
        'post_type' => array('new'),
        'post_status' => array('publish'),
        'post_type' => 'new',
    		'orderby' => 'date', // we will sort posts by date
    		'order'	=> $_POST['date'], // ASC or DESC
        'tax_query' => array(
          array(
            'taxonomy'  => 'industry_category',
            'field'     => 'term_id',
            'terms'     => $_POST['categoryfilter'],
          )
        ),
      );
    } else {
      $args = array(
        'post_type' => array('new'),
        'post_status' => array('publish'),
        'post_type' => 'new',
    		'orderby' => 'date', // we will sort posts by date
    		'order'	=> $_POST['date'] // ASC or DESC
    	);
    }


    // The Query
    $ajaxposts = new \WP_Query( $args );

    $response = '';

    // The Query
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            $response = App\template('partials/content-cards');
        }
    } else {
        $response = 'error';
    }

    echo $response;

    die; // leave ajax call
}

Again, sorry if I’m being dense but have been stuck on this a little while now and feel like there’s an easy solution, I’m just not using right syntax.

    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            $response = App\template('partials/content-cards');
        }
    } else {
        $response = 'error';
    }

There are a couple issues here that could be contributing to your problem:

  1. When you call template you’re passing only a the name of your template. You have to pass data in order for the template to have anything to render. i.e. App\template('partials.content-cards', ['some_variable' => $that_variables_data])
  2. Every iteration of your loop is overwriting the $response variable because you keep reassigning the output of template(). If you want to concatenate, you could using something like .= instead of =.
  3. Usually we use dot notation when specifying partials, i.e. App\template('partials.content-cards'). I think Blade should be capable of understanding /, but using the dot is generally a little safer.
1 Like

Thank you. Will try this out. I forgot to add that currently this function is in app/setup.php. Could that also be causing an issue, Is there a better working practice? I have the AJAX running in it’s own JS file that’s been added to the manifest but I wasn’t sure if I was placing this PHP function in a weird place, it seems to run the AJAX fine fine though.

So long as the function runs, its location is probably immaterial.

1 Like

Still no dice I’m afraid.

The AJAX is responding with an error. I’ve tried just trying to output a basic html without passing any variable into the template partial as well. Here’s what I currently have -

ajax.js

$('#filter').submit(function(e) {
  e.preventDefault();
  var url = $('.header .brand').attr('href') + 'wp-admin/admin-ajax.php';
  var form = $(this);
  var formdata = $(form).serialize();
  $.ajax({
    type: 'POST',
    url: url,
    dataType: "html",
    data: formdata,
    success: function(response) {
      console.log(response);
      $('.additonal-posts').html(response);
    },
    error: function(jqxhr, status, exception) {
      console.log(response);
    }
  });
});

setup.php

add_action('wp_ajax_get_ajax_posts',  __NAMESPACE__ . '\\get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts',  __NAMESPACE__ . '\\get_ajax_posts');

function get_ajax_posts() {
  // Query Arguments
  if(isset( $_POST['categoryfilter'] ) ) {
    $args = array(
      'post_type' => array('new'),
      'post_status' => array('publish'),
      'post_type' => 'new',
    	'orderby' => 'date', // we will sort posts by date
    	'order'	=> $_POST['date'], // ASC or DESC
      'tax_query' => array(
        array(
          'taxonomy'  => 'industry_category',
          'field'     => 'term_id',
          'terms'     => $_POST['categoryfilter'],
        )
      ),
    );
  } else {
    $args = array(
      'post_type' => array('new'),
      'post_status' => array('publish'),
      'post_type' => 'new',
  		'orderby' => 'date', // we will sort posts by date
  		'order'	=> $_POST['date'] // ASC or DESC
  	);
  }


  // The Query
  $ajaxposts = new \WP_Query( $args );

  $response = '';

  // The Query
  if( $ajaxposts->have_posts() ) :
		while( $ajaxposts->have_posts() ): $ajaxposts->the_post();
			$response .= App\template('partials.ajax-cards');
		endwhile;
		wp_reset_postdata();
	else :
		echo 'No posts found';
	endif;


  die; // leave ajax call
}

basic partial template (no variables, PHP, blade)

<div class="col-lg-4 col-sm-6 col-12">
  <h2 class="entry-title"><a href="#">title</a></h2>
</div>

Apologies if this is simple.

Can you post the error?

Undefined for responseStatus and ‘this site is experiencing technical dificulties’ for responseText.

If I try and log the response instead then I get the screenshot attached.

36

I would recommend turning on debugging do you can generate a log file and determine where the error is coming from:

// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );

// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

More info: https://wordpress.org/support/article/debugging-in-wordpress/