tags:

views:

32

answers:

1

Hi all,

When I was doing some self-learning on JQuery Ajax in Cakephp,
I found out some strange behaviour in the JQuery Alert Box.

Here are a few lines of code of the JQuery Ajax I used:

 $(document).ready(function(){  
        $(document).change(function(){ 
            var usr = $("#data\\[User\\]\\[name\\]").val();
            $.post{"http://www.mywebsite.com/controllers/action/",
                usr,
                function(msg){alert(msg);}
            }
        });
    });   

The Alert box shows me a message returned from the Action:

Helloworld <!--0.656s-->

I am not sure why the number of time consumption was displayed in the Alert box,
since it was not in my code as follows:

function action($data=null){
    $this->autoRender = false;
    $result2=$this->__avail($data);           
    if($result2==1)
        {return "OK";}
    else
        {return "NOT";}           
}

CakePHP rteurned some extra information in the Alert box.

Later I altered a single line of code and tried out this instead,
and the time consumption was not displayed on screen then:

$(document).ready(function(){  
            $(document).change(function(){ 
                var usr = $("#data\\[User\\]\\[name\\]").val();
                $.post{"http://www.mywebsite.com/controllers/action/",
                    usr,
                    function(msg){$("#username").append('<span>'+msg+</span'>);}
                }
            });
        });   
+2  A: 

This is normal. CakePHP usually inserts a timestamp for every views. Just add Configure::write('debug', 0) to the first line of your action to avoid the timestamp from being inserted.

So your action should look something like this:

function action($data=null){
  Configure::write('debug', 0)
  $this->autoRender = false;
  $result2=$this->__avail($data);           
  if($result2==1) {return "OK";}
  else {return "NOT";}           
}

If your action is being for an Ajax request as well as a normal Http request:

function action($data=null){
  if($this->RequestHandler->isAjax()) {
    Configure::write('debug', 0)
    $this->autoRender = false;
    $result2=$this->__avail($data);           
    if($result2==1) {return "OK";}
    else {return "NOT";}           
  } else {
    //Not Ajax Request. 
  }
}

Also make sure to add RequestHandler to the components variable in your AppController as well.

var $components = array('RequestHandler', . . . . . . );
Sunny
If you are doing this many times in your application you can also put the debug-switching code in `AppController::beforeRender()`.
deizel