sending data via ajax in Cakephp

99封情书 提交于 2019-12-06 11:59:49

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

I will give you some example. In my case, list out book list as a smart search while typing on text box.

$( ".selectBook" ).each(function(){
    $(this).keyup(function( event ) {
        var tri = $(this).val();
        var oPrnt = $(this).parents('.smartsearch');
        var str = '';
        if(tri.length > 2){
            $.ajax({
                type: "POST",
                url: "/utility/getbooks/",
                data: JSON.stringify({string: tri, activeonly:false}),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                   $.each(data, function(key, val) {
                                str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
                    }); 
                    oPrnt.find("ul.result").html(str);
                },
                error: function (errormessage) {
                    oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
                }
            });
            oPrnt.find("ul.result").slideDown(100);
        }

    });
});

And in the controller, action (getbooks Action in UtilityController in my case)

public function getbooks($string = '', $activeonly = true){

        $this->autoRender = false;

        if( $this->request->is('ajax') ) {
            $data = $this->request->input('json_decode');
            $string = $data->string;
            $activeonly = $data->activeonly;            
        }

        $aReturn = array();
        // ... fetch books data from DB goes here...
        $aResult = $this->Book->fetch('list');
        foreach($aResult as $r){
            if(isset($r['bookname'])){
                $aReturn[$r['id']] = $r['bookname'];
            }
        }            
        return json_encode($aReturn);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!