Difference between php echo and return in terms of a jQuery ajax call

marky picture marky · Apr 11, 2012 · Viewed 9.6k times · Source

I was having trouble getting a jQuery Ajax call's success function to work properly and it was pointed out to me that the reason was that my PHP function was using return $result when I should be using echo $result.

Changing the PHP function that the Ajax called from "return $result" to "echo $result" fixed the problem, but why? There's loads of explanations as to the difference between the two (return and echo) in terms of PHP scripts, but how do they differ when sending that value to an Ajax call?

Answer

Daniel Ribeiro picture Daniel Ribeiro · Apr 11, 2012

Well, the ajax call reads the response from the server, and that response must be rendered as some type of readable data, such as application/json or text/html.

In order to write that data, you need to echo it from the server with PHP.

The return statement doesn't write data, it simply returns at the server level.