Cakephp 3 Ajax Request Response from controller action
<p>Im trying to get Cakephp 3 send a json reply to my javascript function when i call it but i dont know the correct way to do it..</p>

<p><strong>JS function:</strong></p>

<pre><code>function add(){
        //serialize form data 
        var formData = $('#newquestion').serialize(); 
        //get form action 
        var formUrl = $(this).attr('action'); 
        $.ajax({ 
            type: 'POST', 
            url: formUrl,
            data: formData, 
            success: function(status){                 
                    console.log('content='+status);  
            }, 
            error: function(xhr,textStatus,error){ 
                alert(error); 

        } });  

}
</code></pre>

<p><strong>CakePHP 3 action:</strong></p>

<pre><code>public function addajax(){      

        if ($this-&gt;request-&gt;is('ajax')) {       

            $status['msg']="this is a message from cake controller";                
            $this-&gt;response-&gt;body(json_encode($status));

            return $this-&gt;response;

        }
}
</code></pre>

<p><strong>Question:</strong>
The above cakephp action works and sends the correct output but is it correct;
Am i not suppose to use an ajax view or ajax layout?</p>

<p>When i use serialize as below it doesnt work, comes up as "undefined" in the javascript function function. What am i doing wrong? and whats the correct way to do it?</p>

<p>Is the below example not correct also?</p>

<pre><code>public function addajax(){      

        if ($this-&gt;request-&gt;is('ajax')) {       
            //$this-&gt;viewBuilder()-&gt;layout('ajax');         
            //$this-&gt;autoRender = false; // Set Render False    


            $status['msg']="this is a message from cake controller";            

            $this-&gt;set(compact('status'));
            $this-&gt;set('_serialize', ['status']);


            //$this-&gt;response-&gt;body(json_encode($status));
            //return $this-&gt;response;

        }
    }
</code></pre>

<p>PS: i have enabled JSON and XML routing and views.</p>