How to properly use wp.ajax.post?

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'];
   }
   wp_die();
});

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)) {
    e.preventDefault();
    window.wp.ajax.send('example_action', {
        data: { foo: $('.some-field').val() },
        error: function( response ) {
            console.log(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() });

console.log(post);
// logs: {state: ƒ, always: ƒ, then: ƒ, promise: ƒ, pipe: ƒ, ...}

post.done(function(v) {
    // won't be executed
    console.log(v);
});

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

1 Answer
1

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.

Leave a Comment