abdgstywn abdgstywn - 4 months ago 27
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:

$(document).ready(function(){
$("#mybutton").click(function(){
var userdata = {username : $("#UserUsername").val()};
$.ajax({
type:'POST',
url: 'http://localhost/mycakephp/tests/',
data: userdata,
success: function(data){
alert(data.str);
}
});
});
});


The controller class:

<?php
class TestsController extends AppController {

public $name = 'Tests';

function index(){
$this->autoRender=false;
$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

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.