Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 913
marky Avatar asked Apr 11 '12 13:04

marky


People also ask

What is the difference between PHP echo and PHP return?

Echo is for display, while return is used to store a value, which may or may not be used for display or other use.

How ajax operation differ from a PHP code?

Summary: 1. AJAX is a group of technologies that allows web applications to retrieve data from the server asynchronously; PHP is a scripting language designed to produce dynamic web pages.

What is the return type for an ajax call?

The problem ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.

What does an ajax request return?

It receives the returned data and the value of dataType , and must return the (possibly altered) data to pass on to success . success callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object.


2 Answers

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.

like image 190
Daniel Ribeiro Avatar answered Sep 17 '22 17:09

Daniel Ribeiro


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

like image 37
rael_kid Avatar answered Sep 16 '22 17:09

rael_kid