0

In this script, using php's return will not work, whereas echo will. Thing is, if I use echo, and someone where to access the page directly, they would be able to see the output without the formatting.

<script type="text/javascript">
$(function() {

    $('.callAppend').click(function() {
             $.ajax({
                type: 'GET',
                url:  'recent.php',
                dataType:'HTML',
                cache:false,

                success: function(data){
                console.log(data);

                //}       

              },

            });    

        return false;
    });
});
</script>

This the php script

<?php
$feedback = 'Hello this is the php page';

return $feedback; //Use echo, and all works fine.
?>
Norman
  • 6,159
  • 23
  • 88
  • 141

2 Answers2

2

return is used for returning a value from a function to another piece of PHP code.

jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.


This SO answer provides a solution to only allow an AJAX script to be called by that type of request: Prevent Direct Access To File Called By ajax Function

Even though it is checking for 'XMLHttpRequest', someone could make this type of request from something else other than you weboage.

Community
  • 1
  • 1
afuzzyllama
  • 6,538
  • 5
  • 47
  • 64
  • Any other way to do this? Instead of using echo? – Norman Dec 19 '12 at 04:53
  • [print()](http://php.net/manual/en/function.print.php) can do the same thing as `echo`, but I think @irrelephant comment is a valid point. – afuzzyllama Dec 19 '12 at 04:55
  • Use `echo`, though - http://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo – irrelephant Dec 19 '12 at 04:56
  • @Norman - why do you not want to use `echo`? Why are you trying to use `return`? – afuzzyllama Dec 19 '12 at 04:58
  • You can use print, printf or any PHP functions that write to output. Or you can close PHP tag write HTML code directly after it. – Son Nguyen Dec 19 '12 at 05:00
  • Ok. I'll stick to echo. Why I don't want to use echo is, like I said, if a user where to type the url of that php page, they'd be able to see thing without the formatting etc. But I can see it's the same case even on this site. I took a url from firebug and entered it in the browser, and could see it all. So I'm no exception. – Norman Dec 19 '12 at 05:01
  • @Norman - There might be help for you [here](http://stackoverflow.com/questions/1756591/prevent-direct-access-to-file-called-by-ajax-function) – afuzzyllama Dec 19 '12 at 05:04
2

When you use AJAX to load a URL, you're loading the raw output of that URL. Echo produces output but return doesn't. You'll need to do some reason on the subject of OOP to understand what the purpose of return is.

Echo is the correct way to send output.

Nick Coad
  • 3,623
  • 4
  • 30
  • 63