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?

3 Answers 3


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

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

$resp = array(
    'success' => true,
    'data'    => $data
  • How do you output $resp?
    – Daniel
    May 11, 2018 at 21:19
  • Depends on what you're doing. It wasn't part of the original question, so I don't know the context in which they were using that variable. They were probably using it in wp_send_json(). Oct 18, 2018 at 11:40

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);
    if ($p_query->have_posts()) {
        while ($p_query->have_posts()) {
            get_template_part('template-parts/content', $post_type);
    } else {
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


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

so It'll be:

dataType: 'json',

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.