4

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 !

1
  • don't echo put return 'SUCCESS';exit(); and try Commented May 7, 2015 at 17:44

2 Answers 2

4

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']); 
Sign up to request clarification or add additional context in comments.

2 Comments

or use the Ajax plugin and cleanly return a json array to work with in the view. Then you dont need the is(ajax) check.
you saved my day. Works perfect
2

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"} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.