2

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?

6

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
);
  • How do you output $resp? – Daniel May 11 '18 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(). – Jacob Peattie Oct 18 '18 at 11:40
0

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

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.