zelocalhost
zelocalhost

Reputation: 1183

Get variable of a controller with jquery

i try to get a result of a variable of a controller , like this :

$('#ajax-test').click(function() {
     $.get('/ajax', function(data) {
      $('#ajax-test').html('$result').html(data);
     });
});

i have only errors, so what is the correct way ?

Upvotes: 0

Views: 2271

Answers (2)

Vikash Pathak
Vikash Pathak

Reputation: 3562

If you want to get value from the controller variable. You should have to specify the code as follow.

<script type="text/javascript">
$(function(){
    $('#ajax-test').click(function() {
        $.get('/ajax', function(data) { // no action specified so index will default.
          $('#ajax-test').html('$result').html(data);
        });
    });
})
</script>

and in your controller.

public function index(){
   $this->layout = null; // layout not required.
   $this->autoRender = false; // view file is also not required.

   // other statements.
   echo $result;
}

Upvotes: 3

Vainglory07
Vainglory07

Reputation: 5273

if you are trying to get the value of your controller just make your controller echo or display the the result:

 public function ajax() {
     echo $result;
 }

so that the function(data) will get the function value automatically.

if you really want to get the value including the variable then put your values in an array put it in json and parse it in your jquery:

 public function ajax() {
     $array['result'] = 'hello world'; // where result is your variable name
     echo json_encode($array);
 }

Upvotes: 2

Related Questions