L_air
L_air

Reputation: 53

Jquery ajax call in Cake PHP 3.0


Hi, I'm trying to make a ajax request to the view A from the controller B like this :

In the view A :

var tab = new Array();
    function updateResult(){
            $.ajax({
                type:"POST",
                url:"<?php echo Router::url(array('controller'=>'B','action'=>'viewresult'));?>",
                dataType: 'text',
                async:false,
                success: function(tab){
                    alert('success');
                },
                error: function (tab) {
                    alert('error');
                }
            });
    }

In the controller B:

public function viewresult()
{
echo 'SUCCESS';
}

The problem is that in the 'response' of ajax, I've 'SUCCESS' but also the entire view A, I don't understand why... I want only 'SUCCESS'...

Thanks in advance !

Upvotes: 4

Views: 13920

Answers (2)

Abhishek
Abhishek

Reputation: 805

Detect if its ajax as per following code in cakephp way :

    if($this->request->is('Ajax')) //Ajax Detection
    {
        $this->autoRender = false; // Set Render False
        $this->response->body('Success');
        return $this->response;
    }

Check here for more detectors - http://book.cakephp.org/3.0/en/controllers/request-response.html#Cake\Network\Request::addDetector

You can also use $this->Url->build instead of including Router for creating links in view.

echo $this->Url->build(['action'=>'index']);

Upvotes: 4

marian0
marian0

Reputation: 3337

The easiest way to achieve it is adding die() at the end of your function so it prevents to load whole layout:

public function viewresult()
{
    echo 'SUCCESS';
    die;
}

OR

public function viewresult()
{
    die('SUCCESS');
}

But more conventional way is using JSONView. Your action should look as follows:

public function viewresult()
{
    $this->set('text', 'SUCCESS');
    $this->set('_serialize', ['text']);
}

You also have to load RequestHandler component in initialize() method in your controller:

public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
}

You need to set allowed extensions for all routes connected later in routes.php:

Router::extensions('json', 'xml');

Now you can access your action adding extension .json at the end of it's URL, so you need to modify ajax call url:

url:"<?php echo Router::url(array('controller'=>'Main','action'=>'viewresult', '_ext' => 'json'));?>"

That's all, but keep in mind that this solution force you to handle JSON array in response. In this example output will be looks as follows:

{"text": "SUCCESS"}

Upvotes: 2

Related Questions