On my jQuery ajax function, I output the data returned from a PHP script like this:
jQuery(this).html(data);
The PHP function which returns the data contains:
echo 'Please do this again.';
return;
By some reason, it outputs as:
Please do this again.0
So it adds a 0
at the end. Why does this happen and what can I do to fix it?
You should die
inside of your ajax action handler as follows:
echo 'Please do this again.';
// Don't return, die!
// return;
die;
Your code is performing exactly as expected. The problem is that you're using WordPress and have not stopped execution inside of your action handler function.
WordPress handles ajax calls via wp-admin/admin-ajax.php
, and the last lines will produce the output 0
:
// Default status
die( '0' );
Inside of your action handler function, you should call die
yourself to ensure that the end of this file is never reached and 0
is not appended to your response.
Quick Answer (I will explain more later):
With return;
you produce that extra output, that gets interpreted to 0
.
Eighter remove that return;
or replace it with an exit;
to stop php from executing.
Other possibility is to do return 'Please do this again.';
if you are outside of functions.