I'm running the following handler to process request to a custom post type's contents
add_action('wp_ajax_uipp_get_button_content', 'uipp_get_button_content');
add_action('wp_ajax_nopriv_uipp_get_button_content', 'uipp_get_button_content');
function uipp_get_button_content() {
if (!isset($_POST['button_id']) || !is_numeric($_POST['button_id'])) {
wp_send_json_error(['message' => 'Invalid button ID.']);
}
$button_id = intval($_POST['button_id']);
$button_content = apply_filters('the_content', get_post_field('post_content', $button_id));
if (!$button_content) {
wp_send_json_error(['message' => 'Content not found.']);
}
wp_send_json_success(['content' => $button_content]);
}
And then attempting to print the resulting content on a page with:
fetch(ajax_object.ajax_url, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
action: "uipp_get_button_content",
button_id: button_id,
}),
})
.then(response => response.json())
.then(data => {
if (data.success) {
revealContainer.innerHTML = data.content;
console.log(data.content);
} else {
revealContainer.innerHTML = `<p>Error: ${data.message}</p>`;
}
})
.catch(error => {
revealContainer.innerHTML = "<p>Failed to load content.</p>";
});
Inspecting in the console (Network > Fetch/XHR), fetching was a success, I can see the content there. But on the frontend, it always prints "undefined". enter image description here
Nothing in the console in the way of errors - error_log and debug_log are both empty!
Where could I be going wrong?
In the handler, I even tried replacing the sent data with just a simple "Hello", thinking that there might be special characters from the post content's HTML, styles, scripts, that could be interfering or causing malformed code.
Replaced:
wp_send_json_success(['content' => $button_content]);
with:
wp_send_json_success(['content' => "Hello"]);
Same issue, still undefined.