1

I wrote a plugin that calls a PHP function from JQuery and the php sends a json response back to the Jquery using wp_send_json(). The functions are all called successfully, but the json request sends a lot of html to the jquery function every time. How do I make the json sent by the php function only a specific message?

JQUERY:

jQuery( document ).ready( function() {

        jQuery( 'body' ).on( 'click', '.wpm_mail_link', function( e ) {

            var varData = 'name:foobar&email=bar@baz.foo';      

      jQuery.ajax({
        type: "POST",
        action: "wp_ajax_send_email",
        url: my_ajax_obj.ajax_url,
        data: varData,
        success: function(data) {
          console.log('Ajax request successful');
          console.log(data.message);
        }
      });



        });

});

PHP:

    public function send_email() {
        $response = array(
        'message' => 'Sent',
        'ID'      => 1,
    );

    wp_send_json( $response );
    }
  • Everything looks right to me. There might be something else going on that has nothing to do with this code, but is conflicting with it. – MikeNGarrett Apr 13 at 0:22
  • the PHP function IS called by the Ajax request so idk... oh and I did remember to add_action( 'wp_ajax_send_email', [ $this, 'send_email' ] ); and add_action( 'wp_ajax_nopriv_send_email', [ $this, 'send_email' ] ); so that it would all work. I have used AJAX successfully in OOP before, so I don't think it's related to that but I just don't know... – brothman Apr 13 at 0:38
  • Does your button also do something else? Try e.preventDefault() in your click function in js. – MikeNGarrett Apr 13 at 0:41
  • Have you tried specifying dataType: 'json' in your Ajax call? – Howard E Apr 13 at 0:50
  • ok my wordpress installation started showing new errors tonight which led to me commenting out some unrelated lines that was using JQuery... anyway, now the function is printing 'undefined' instead of that big block of html from before... does that give any clues? – brothman Apr 13 at 2:55
0

Fixed it! I was getting a false positive with the ajax request. I thought it was going through but returning 'undefined' but I was actually using the wrong url.

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.