0

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..

JS function:

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

        } });  

}

CakePHP 3 action:

public function addajax(){      

        if ($this->request->is('ajax')) {       

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

            return $this->response;

        }
}

Question: 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?

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?

Is the below example not correct also?

public function addajax(){      

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


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

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


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

        }
    }

PS: i have enabled JSON and XML routing and views.

3
  • Your action method is correct just don't forget to add at the beginning of your method : $this->autoRender=false; . However i can't tell that it is the correct method of using ajax in cakephp 3. This article might help :dereuromark.de/2014/01/09/ajax-and-cakephp Commented May 14, 2016 at 14:57
  • The article @user3078643 suggests is for cakephp 2.0 not 3.0. Commented May 14, 2016 at 16:42
  • @user221931 There is a section about cakephp 3.x Commented May 14, 2016 at 22:07

2 Answers 2

4
$this->response->withType('application/json')->withStringBody(json_encode($format));

with $format is your array.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't know why that was downvoted, as this is correct answer.
-1

Your are will send php array via json, then you are encode an array in php and parse the response in js function

Try this in your CakePhp 3 action:

public function addajax(){ 

    $this -> autoRender = false;     

    if ($this -> request -> is('ajax')) {       

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

        return json_encode($status);

    }
}

JS function:

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){  
            var json = JSON.parse(status);             
            console.log('content='+json.msg);  // .msg is name of your index $status['msg']
        }, 
        error: function(xhr,textStatus,error){ 
            alert(error); 
        } 
    });  
}

2 Comments

CakePHP ships not only with automated request handling and JSON serialization, but the request object also contains proper methods for defining the response (body, headers, etc.), which is what the OP is trying in the first example. Your example just makes things worse by side-stepping all that, and causing an exception because controller actions are only allowed to return either null, or an instance of \Cake\Network\Response. Also note that the autoRender option has no effect when returning a response object.
ok then what is the correct solution @ndm add this $this->set(compact('status')); $this->set('_serialize', ['status']); in my php function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.