After struggling for quiet while with the wp utils functions send and post. I didn't manage to get one of them working properly after all.

But I did manage to get a response, however I don't know why this works and the other things I tried didn't.

For this topic, the PHP is not relevant. To prevent any confusions, consider I'm using the following PHP:

add_action('wp_ajax_example_action', function() {
   if (!empty($_REQUEST['foo'])) {
       print 'Foo: '.$_REQUEST['foo'];

The javascript what ALWAYS returned all the printed/echoed text in the triggered php function, no matter what conditions were met.

$('.some-button').click(function(e)) {
    window.wp.ajax.send('example_action', {
        data: { foo: $('.some-field').val() },
        error: function( response ) {

Here the result of a simple test:

| $('.some-field').val() | console.log(response) |
| "bar"                  | "Foo: bar"            |
| ""                     | "Foo: "               |

I tried a lot of things with the send() method as well as with the post() method. But nothing seems to work unless it's exactly like the javascript above. Yes it only works with property error not with done or success neither with fail or always.

Edit #1

Have a look at the following code where I explain what happens with the code that doesn't return a response.

let post = window.wp.ajax.post('example_action', { foo: $('.some-field').val() });

// logs: {state: ƒ, always: ƒ, then: ƒ, promise: ƒ, pipe: ƒ, ...}

post.done(function(v) {
    // won't be executed

However in the network section of my developer tool the request and response are correctly shown.

  • Do you have a sample of the javascript code that isn't working? – czerspalace Aug 31 '17 at 17:51
  • and what is being actually sent (look in the network section of the browser developer tools) – Mark Kaplun Aug 31 '17 at 19:45
  • @czerspalace please have a look at the code in the first edit of my question. – luukvhoudt Sep 1 '17 at 11:31
  • @Fleuv review my sample code, which i have added, all ready i worked on it. – Ravi Patel Sep 1 '17 at 11:50

wp.ajax.post will need you to wrap your response with wp_send_json_success. It will add additional parameter on your json response with success flag.

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.