0

Added Note that this process is in a WP plugin, using thw WP API, so I believe this is appropriate for this SO and should not be closed.

The following REST call is used to get a specific comment:

var comment_id = 239;   
response = wp.apiRequest( {   // ajax post to set up comment redact meta value
                path: 'wp/v2/comments/' + comment_id  ,
                method: 'POST',
                data: thedata
            } );

This returns a JSON object, and the next step is to get the comment text from the JSON object, which contains these values (not complete response, and sanitized):

{
  "id": 239,
  "post": 424,
  "parent": 0,
  "author": 1,
  "author_name": "username",
  "author_url": "",
  "date": "2023-02-20T12:43:02",
  "date_gmt": "2023-02-20T20:43:02",
  "content": {
    "rendered": "<div class=\"comment_text\"><p>here is a comment</p>\n</div>"
  },
  "link": "https://example.com/my-test-post/#comment-239",
  "status": "approved",
  "type": "comment",
}

My problem is I can't figure out how to get the 'rendered' value. I have tried this:

response_array = JSON.parse(response.responseText);

but get an error:

JSON.parse: unexpected character at line 1 column 1 of the JSON data

Still learning JSON, and have done many searches to now avail.

What JS code will get me the comment text out of the response object?

2
  • Thanks. The question is WP-based, I believe, as it is using the WP REST API to get data. Think it is valid for this SO, and should not be closed. Commented Feb 23, 2023 at 19:33
  • You mean, "this WPSE"? And to be honest, I was actually going to retract my close vote, but I forgot and when I remembered it back, this question was already closed. But the thing that's specific to WordPress in your post, is the use of wp.apiRequest() - and you didn't know what it returns (one could guess or do console.log( response ), but it's better when explicitly explained).
    – Sally CJ
    Commented Feb 24, 2023 at 0:42

2 Answers 2

0

A brief introduction and what does wp.apiRequest() return

wp.apiRequest() is one of the three JavaScript API written by WordPress (the other two JavaScript APIs are the Backbone JavaScript Client and wp.apiFetch()), which we can use to communicate with the WordPress REST API, and as for wp.apiRequest(), it uses jQuery.ajax() which returns a jqXHR object that implements the Promise interface, giving it all the properties, methods such as .then(), and behavior of a Promise. See https://api.jquery.com/Types/#Promise

The issue with your code

Originally, I thought the AJAX request had not been resolved (or not yet complete) and thus response.responseText was an undefined, instead of a JSON-encoded string.

Demonstration of the issue:

const response = wp.apiRequest( { ... } );
// Note: That `response` is a jqXHR object.

// At this point, responseText is still an undefined.
console.log( 'before calling .then()', response.responseText, response );

response.then( ( comment, status, jqXHR ) => {
    // At this point, responseText is filled and it's a proper JSON-encoded string.
    console.log( comment, jqXHR.responseText, response.responseText );
} );

// At this point, responseText is also still an undefined.
console.log( 'after calling .then()', response.responseText, response );

But then after reading your answer or checking your code there, if you actually did something like this:

.then( function( response ) {
    // Parse the JSON response into a JavaScript object.
    response_array = JSON.parse(response.responseText);
} )

Then that response.responseText was also (likely) an undefined, because the REST API would not add such property by default, and you should have actually read it from the third parameter, i.e. the jqXHR object above.

But you don't have to manually parse the response text into an object, because the first parameter is already an object representation of the response text.

How to properly get the comment text (the value of content.rendered) and other data

You can use .then() or these jQuery-specific methods: .done() (and .always()).

There's already an example above, which uses .then(), but here's another example:

wp.apiRequest(
    {
        path: 'wp/v2/comments/' + comment_id,
        method: 'POST',
        data: thedata
    }
).then(
    function ( comment ) {
        console.log( comment.content.rendered );
    }
);

If you want wp.apiRequest() to return the comment object instead of jqXHR, then you can use await and async. Here's an example which uses IIFE (Immediately Invoked Function Expression):

async function editComment( comment_id, thedata ) {
    const comment = await wp.apiRequest(
        {
            path: 'wp/v2/comments/' + comment_id,
            method: 'POST',
            data: thedata
        }
    );

    const commentText = comment?.content?.rendered;
    console.log( commentText ); // This is logged first.

    return comment;
}

// This is an IIFE.
( async () => {
    const comment = await editComment( 123, { content: 'new content here' } );
    console.log( 'after', comment ); // This is logged after the one above.
} )();
2
  • Thanks. Your answer was correct (and marked as correct), but see my additional answer on how I figured it out before I saw your answer. Commented Feb 24, 2023 at 18:02
  • 1
    Thanks a lot for marking my answer as correct, but I decided to revise it, and hopefully the revision helped you more.
    – Sally CJ
    Commented Feb 25, 2023 at 0:42
0

I will mark @SallyCJ's request as correct, but I figured out the answer prior to reading hers (which is similar to what I used successfully), and wanted to supplement her answer with the code that I used to fix the issue.

Note that the answer was provided with ChatGPT, and I verified it worked properly. Here's the relevant code, similar to what SallyCJ posted:

    response = wp.apiRequest( {
    path: 'wp/v2/comments/' + comment_id,
    method: 'POST',
    data: thedata,
    fields: 'content',
} ).then( function( response ) {
    // Parse the JSON response into a JavaScript object
    //console.log(response);
  const contentRendered = response.content.rendered;
console.log(contentRendered);

} ).catch( function( error ) {
    console.error( error );
} );

My issue was trying to use JSON.parse() on the response, to parse the response into a JS JSON object. But it already was the correct type of object to use. Trying to parse it resulted in the error 'unexpected character at line 1 column 1 of the JSON data'.

Note that I had done hours of searching here and other places to get an answer, and the ChatGPT gave me the correct answer. I am aware that ChatGPT answers may not be valid or accepted here, but I tested it's answer and it worked properly.

1
  • 1
    I have no comments regarding ChatGPT, however as for this - "it already was the correct type of object to use" - remember that the response as in response = wp.apiRequest vs the one in .then( function( response ) are not the same type of object. As stated in my answer, that first response is a jqXHR object, whereas the other response is a plain object and it's also available or filled (after the AJAX request is complete) in a property named responseJSON of the jqXHR object.
    – Sally CJ
    Commented Feb 25, 2023 at 0:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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