开发者

JavaScript in CakePHP's controller

开发者 https://www.devze.com 2023-04-02 16:13 出处:网络
In my CakePHP view, I call method in controller, using jQuery: function placeSensors(nk) { $.ajax({ type:\'post\',

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 $componen开发者_如何转开发ts = 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>


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.


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();  

             }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消