get_template_part not working with ajax

I loaded some contents by ajax, When i try something like this:

$resp = array(
    'success' = true,
    'data' = 'the content here'
);

it's working without any issues but if i used something like this:

$resp = array(
    'success' = true,
    'data' = get_template_part( 'templates/update', 'profile' )
);

it gives me SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data.

the content here{"success":true,"data":null}

What's the problem with get_template_part?

Topic get-template-part php Wordpress

Category Web


This worked for me! don't forget to set the datatype to json in your JS ajax function

so It'll be:

dataType: 'json',

Since this had me scratching heads for a while too; here's the code i came up with if it can be useful to anyone.

Register and localize the JS script, here's some good practical info for the basic WP Ajax gen

The wp_ajax function itself :

    function fpost()
{
    $post_type = sanitize_text_field($_POST['post_type']);
    $post_id = intval($_POST['post_id']);
    $args = array(
        'post_type' => $post_type,
        'post_status' => 'publish',
        'p' => $post_id,
    );
    $p_query = new WP_Query($args);
    ob_start();
    if ($p_query->have_posts()) {
        while ($p_query->have_posts()) {
            $p_query->the_post();
            get_template_part('template-parts/content', $post_type);
        }
        wp_reset_postdata();
        wp_send_json_success(ob_get_clean());
    } else {
        wp_send_json_error();
    }
    die();
}
add_action('wp_ajax_nopriv_fp', 'fpost');
add_action('wp_ajax_fp', 'fpost');

The JS sends post_type and post_id, and WP returns 2 objects; the templated content + "success" (which is much helpful..)

hope that helps


get_template_part() includes the PHP file, which will break $resp. You need to use output buffering to capture the output into a variable:

ob_start();
get_template_part( 'templates/update', 'profile' );
$data = ob_get_clean();

$resp = array(
    'success' => true,
    'data'    => $data
);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.