Search code examples
phpajaxcakephpcakephp-2.0cakephp-2.1

sending data via ajax in Cakephp


i am new to cakephp and trying to send data from ajax to my controller action.. i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh

here is my code ..

 <a  class="button anthracite-gradient" onclick="openPrompt()">submit </a>

my javascript

 function openPrompt()
{
var cancelled = true;

$.modal.prompt('Please enter a value:', function(value)
{

    $.ajax({
        type:"POST",

        url:"/cakephp/controller/action/",
        success : function(data) {
           alert(value); //value right now is in this variable ... i want to send this variable value to the controller

        },
        error : function() {
           alert("false");
        }
    });


    }, function()
   {

    });
    };
</script>

myController

 public function action(){
    if( $this->request->is('ajax') ) {
      $new = $this->request->data; 

        echo "ok"
        return;
    }
}

i want to first get the value here and then send the response to may ajax request


Solution

  • Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller

     function openPrompt()
    {
    var cancelled = true;
    
    $.modal.prompt('Please enter a value:', function(value)
    {
    
        $.ajax({
            type:"POST",
            data:{value_to_send:value}, 
            url:"/cakephp/controller/action/",
            success : function(data) {
               alert(data);// will alert "ok"
    
            },
            error : function() {
               alert("false");
            }
        });
    
    
        }, function()
       {
    
        });
        };
    </script>
    
     public function action(){
        if( $this->request->is('ajax') ) {
         // echo $_POST['value_to_send'];
         echo   $value = $this->request->data('value_to_send');
    
         //or debug($this->request->data);
            echo "ok"
          die();
        }
       }
    

    For more see accessing-post-data