0

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,

  1. I localized admin-ajax into the JQuery script:
    wp_localize_script( 'cp_script', 'cp_script', new array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), ) );

  2. I added the ajax action:
    add_action( 'wp_ajax_chatpress_erase_all_messages', new array( $this, 'chatpress_erase_all_messages' ) );

  3. 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?

7
  • 1. Your JS is expecting a JSON response, so did your "other code" send/output a valid JSON data (and header)? 2. Note that you can't echo anything if your function is (still) calling wp_send_json_success(), e.g. don't do echo 'foo'; wp_send_json_success();
    – Sally CJ
    Jul 28 at 1:40
  • What do you see in the Network tab of the developer tools? What's the actual response? Jul 28 at 6:16
  • @SallyCJ no, the "other code" was echo "test"; and print_r('test'); how would I use the other code to send/output a valid JSON data (and header)?
    – brothman01
    Jul 28 at 13:01
  • @JacobPeattie I updated the question with a screenshot.
    – brothman01
    Jul 28 at 13:02
  • 2
    Those functions work fine for AJAX. The problem is that if you’re also using wp_send_json_ then you’re mixing up other output with JSON meaning that the response is not valid JSON. That’s what Sally was talking about. Jul 28 at 15:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.