I wrote a plugin a few years ago that successfully uses AJAX and then recently I tried to add more of the same functionality but it fails. In the PHP files,
I localized admin-ajax into the JQuery script:
wp_localize_script( 'cp_script', 'cp_script', new array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), ) );
I added the ajax action:
add_action( 'wp_ajax_chatpress_erase_all_messages', new array( $this, 'chatpress_erase_all_messages' ) );
I wrote the php function that is fired:
public function chatpress_erase_all_messages() {
wp_send_json_success( [
'message' => 'foobar',
] );
}
then in the JQuery, I wrote a function to actually call the code:
$('#erase-old').on( 'click', function() {
jQuery.ajax({
type : "post",
dataType : "json",
url : cp_script.ajaxurl,
data : { action: "chatpress_erase_all_messages" },
success: function(response) {
console.log(response);
}
});
});
The request on the network tab looks like:
whenever I test, the output is the success message. This is a new feature that is similar to the old one which has been working. When I add any other code to the PHP function chatpress_erase_all_messages()
, I stop getting the success back and the code does not fire (echo, print_r, wp_die, nothing). I thought I replicated the same steps as with other, similar features but no. Does anyone see what I am doing wrong/why the output is nothing when I actually add code to the PHP function before what is shown above?
wp_send_json_success()
, e.g. don't doecho 'foo'; wp_send_json_success();
echo "test";
andprint_r('test');
how would I use the other code to send/output a valid JSON data (and header)?