4

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.

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

1 Answer 1

3

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.

1
  • I was using wp_send_json() and getting no response in js, I switched to wp_send_json_success() and it works! Jul 30, 2021 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.