user198003
user198003

Reputation: 11151

JavaScript in CakePHP's controller

In my CakePHP view, I call method in controller, using jQuery:

function placeSensors(nk) {
  $.ajax({
    type:'post', 
    url:'/myapp/maps/placeSensors/' + nk, 
    success: function(r) {
      if(r.status = 'ok') {
      }
    }
  });
}

JS in controller is defined with ie.:

class MapsController extends AppController {
  var $name = 'Maps';
  var $helpers = array('Js');
  var $uses = array('Measurings', 'Maps');
  var $components = array('RequestHandler'); // added later, but still the same


function index( $id = null, $value = null ) {
$code = '';
?>
<script type="text/javascript">
  alert('Hello!');
</script>
<?php
return $code;
}

So, with simple code, I can not get alert message on my web form. Very simple code I was using in some other project and it works there, and for some reason this does not work on this one...

I'm really stuck with this one, can you please help me.....

UPDATE: this is response i'm getting by Firebug:

<script type="text/javascript">
  alert('Hello!');
</script>

Upvotes: 0

Views: 5034

Answers (3)

user198003
user198003

Reputation: 11151

Ok, i finally solved this one.

All I needed was to add one form and one text, or even better hidden element on form.

After that everything started to work.

So my mentioned code was ok, all I needed was that one text box......... Hope that somebody can tell me why?

Thank you on all your help and support.

Upvotes: 0

chetanspeed511987
chetanspeed511987

Reputation: 2025

function placeSensors(nk) {
 $.ajax({
   type:'post', 
    dataType:'json',
   url:'/myapp/maps/placeSensors/' + nk, 
   success: function(r) {
     if(r.status) {
          alert(r.code);
     }
   }
 });
}

       class MapsController extends AppController {
           var $name = 'Maps';
            var $helpers = array('Js');
              var $uses = array('Measurings', 'Maps');


        function index( $id = null, $value = null ) {


             }

        // update below code
      function placeSensors( ) {
                $nk = $_POST['nk'];
              echo json_encode(array(
            'status' => true,
            'code' => "code"                
            ));
       exit();  

             }

Upvotes: 1

Ivo
Ivo

Reputation: 5420

You're trying to place code that should be viewed (javascript) by the client, inside a controller. Controller is for business logic, that the client doesn't see.

Place your javascript inside a javascript file in the /webroot/js/ directory.

For interacting with ajax, tell your controllers to use the RequestHandler component to determine that they're being called by ajax. From there you can return simple values, or return a json or xml view.

If that sounds complicated, don't worry about it for now and just start as simple as you need and slowly build up your application.

Upvotes: 1

Related Questions