Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
Does it (the addition of 0) happen even if you're logged out of wordpress? –  murdaugh Oct 4 '13 at 12:06
    
Yes, even if I am not logged into WordPress. –  Radek Oct 4 '13 at 12:14
add comment

1 Answer 1

up vote 13 down vote accepted

The default response from admin-ajax.php is,

die( '0' );

...by adding your own 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.

share|improve this answer
    
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 '13 at 1:12
2  
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. –  userabuser Oct 5 '13 at 1:26
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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