21

Unless I end Ajax processing function by exit() or die(), the Ajax function receives desired and correct output but following by 0.

Any idea why is that happening?

Is that meant to be like that or it could be fixed?

add_action('wp_ajax_get_homepage', 'get_homepage');
add_action('wp_ajax_nopriv_get_homepage', 'get_homepage');

function get_homepage(){
    echo "get_homepage ->";
    exit();
}

I've read at AJAX in Plugins, but why is that necessary?

2
  • Does it (the addition of 0) happen even if you're logged out of wordpress?
    – murdaugh
    Oct 4, 2013 at 12:06
  • Yes, even if I am not logged into WordPress.
    – Radek
    Oct 4, 2013 at 12:14

1 Answer 1

38

The default response from admin-ajax.php is,

die( '0' );

...by adding your own wp_die() or exit() or die() after returning your desired content prevents the default response from admin-ajax.php being returned as well.

It also generally means that your ajax call has succeeded.

Ultimately, to answer your question, it's meant to work this way. What you are doing by exiting after returning your content is the right thing to do.

4
  • Thank you for the explanation. So do I use die() or I check inside ajax for 0 to know that everything was ok?
    – Radek
    Oct 5, 2013 at 1:12
  • 3
    Use die() or exit() after you echo your content/data. In the success/complete callback function of your ajax method, you can then manipulate the data and use it to populate the DOM. You can also do any additional error checking to validate data integrity. You can also do error checking in your PHP callback function prior to output. Essentially exiting after returning your response will ensure you don't also get the 0 along with it. By the way just because you receive a 0 response does not mean your ajax call was 100% successful. However its easy to tell when you inspect your output.
    – Adam
    Oct 5, 2013 at 1:26
  • 1
    You should be using wp_die() added in 2.0.4
    – thrillcode
    Apr 28, 2018 at 4:31
  • @thrillcode unless you need to expose the process of wp_die to other plugins or theme code that can hook onto said process, then, using die or exit is ok. If you intend to release your code as OSS or otherwise, where your code needs to play nice with others, then wp_die would be more preferable, agreed.
    – Adam
    Apr 29, 2018 at 8:12

Your Answer

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

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