</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/10107144/difference-between-php-echo-and-return-in-terms-of-a-jquery-ajax-call" dir="ltr">Difference between php echo and return in terms of a jQuery ajax call [closed]</a>
<span class="question-originals-answer-count">
(4 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2014-07-13 09:13:44Z" class="relativetime">5 years ago</span>.</div>
</div>
</aside>
I have the following code
<?php
$token = '';
if(!empty($_POST['token'])) $token = $_POST['token'];
$url = '';
if(!empty($_REQUEST['url'])) $url = Sanitize($_REQUEST['url']);
if(!filter_var($url, FILTER_VALIDATE_URL)) return 'erro1';
?>
This page is supposed to be executed by AJAX so I'm coding error codes, now if the URL is not valid, I expect it to return erro1
The problem is, it never returns erro1
. I tried dumping the result of the filter_var and it was false
as expected! The page simply executes and return nothing even though the URL is not valid, but if I switch return with an echo, it works.
Why is that? Why is echo working but not return?
</div>
You need to use echo
instead of return
. Your Web server executes the PHP code and serve its output, which you produce using echo
and other printing functions.
Outside of a function, return
interrupts the script.
return
will return a value from a function to the the code that called that function. It can only be used internally within PHP.
Your return
statement is not in a function.
To write data to the HTTP response where JavaScript can read it, you need to use echo
, print
or similar.