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

10,384

Solution 1

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.

Solution 2

An Ajax call uses the response of an HTTP request. A PHP script doesn't generate output by returing, but by echoing.

Solution 3

Ajax calls see data the same way that we do, it reads it as a string. It's basically accessing another web page and "receiving" the result. PHP's 'return' is returning the value on the server only. You need to actually output the data so that when the Ajax call is made, the page it is looking at actually has data written out.

Solution 4

The echo command outputs data to the Standar Output, this is in web browser applications, the client who requested the data. In CLI this print the data on the console. And return command exit the function with a value, but doesn't print anything.

If you want to comunicate between PHP functions, you have to use return. But if you want to output some data, you have to use echo.

Share:
10,384
marky
Author by

marky

I work as a database migration/conversion programmer for a medical software company in rural central Minnesota. Tools used include SQL Server 2005, 2008 and 2012, VS2013, Tortoise SVN.

Updated on June 06, 2022

Comments

  • marky
    marky almost 2 years

    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?