abdgstywn abdgstywn - 1 year ago 90
jQuery Question

CakePHP: Unable to get returned data using AJAX

I want to get the value of a single variable from my Controller class using AJAX request. But it's still cannot get the returned variable. Here's the code I use:

var userdata = {username : $("#UserUsername").val()};
url: 'http://localhost/mycakephp/tests/',
data: userdata,
success: function(data){

The controller class:

class TestsController extends AppController {

public $name = 'Tests';

function index(){
$str = "valid";
return $str;


I want to get '$str' variable, but why the alert() result is still "undefined", which is supposed to be "valid"?

Answer Source

That's because this is not how AJAX requests work. They can't capture any PHP return value as it's not a server-side request nor PHP at all. All it can do it catch the actual HTTP response it gets, being something like HTML or JSON. You can just simply echo the result in your function and it should do:

function index(){
    $this->autoRender = false;
    $str = "valid";
    echo $str; // echo rather than return here

This way $str is then set in the data reposonse (so not data.str) of the AJAX request.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download