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?

4

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

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.