Tag Archives: json

Cakephp3: sending json response message to view

23666Method1:

$this->response->body(json_encode($msg));
return $this->response;

Method2:

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

//controller action

public function test(){		
		
		$msg="this is a call";
		
                //method 1 (chose a method)
		$this->response->body(json_encode($msg));
		return $this->response;	
		
		//method 2
		$this->set('msg', $msg);
		$this->set('_serialize', ['msg']);		
		
}

//javascript function call in view
function delete_all(){
	jQuery.ajax({
			type:'POST',
			async: true,
			cache: false,
			url:'mycontroller/test.json',
			success: function(response){					
				//success
				console.log(response);  				
			},
			error: function(response){					
				console.log(response);
			}
		});
}

 

Send Form data with ajax to cakephp controller

23666The following example shows how to submit a form with AJAX to a Cakephp controller;

Jquery Javascript Funtion;

	/*
	sends the form to the controller, ensure form fields names match up 
	with escpected values.
	*/
	function testajaxaddv3(){		
		jQuery.ajax({
			type:'POST',
			async: true,
			cache: false,
			url: 'http://localhost/mycakeapp/messages/ajaxadd',
			success: function(response) {					
				//success
				console.log(response);                
			},
			error: function(response) {					
				console.log(response);
			},
			data:jQuery('form').serialize()
		});
	}

CakePHP 3 Form:

<?= $this->Form->create(null) ?>
<fieldset>
<legend><?= __('Add Quizzes Answer') ?></legend>
<?php
echo $this->Form->input('message');
?>
</fieldset>

<?= $this->Form->end() ?>
</div>

<?php
echo $this->Form->button('save',['onclick'=>'testajaxaddv3()']);
?>

 

Cakephp3 Ajax data submission example

23666How to create a javascript function to send a AJAX request to your cakePHP controller action;

 

 

function testajaxadd(question_id,answerindex){ 

var mydata=new Object();
mydata.question_id=question_id;
mydata.answerindex=answerindex;

jQuery.ajax({
type:'POST',
async: true,
cache: false,
data: mydata,
url: 'http://localhost/myquiz/questions-answers/ajaxadd',
success: function(response) { 
//success
console.log(response); 
},
error: function(response) { 
console.log(response);
}
});
}

Cakephp controller action;

public function ajaxadd(){

$questionsAnswer = $this->QuestionsAnswers->newEntity(); 
if ($this->request->is('ajax')) {

$questionsAnswer = $this->QuestionsAnswers->patchEntity($questionsAnswer, $this->request->data);

// Added this line which makes the record belong to the logged in user
$questionsAnswer->user_id = $this->Auth->user('id');

if ($this->QuestionsAnswers->save($questionsAnswer)) {

$status['msg']="Saved Record"; 

} else {
$status['msg']="Error Saving Record"; 
}

//return the message to js function
$this->response->body(json_encode($status));
return $this->response; 
}
}

 

How to add REST features to your Cakephp 3 App

23666To add REST features to your CakePHP 3 you simply need to add two lines of code to your controller;

This will allow any action in the controller to be viewed as JSON or XML .

To view your action index as JSON simply;

http://localhost/mycakeapp/mycontroller/index.json

Rest Examples:
http://localhost/mycakeapp/mycontroller/view/1.json

http://localhost/mycakeapp/mycontroller/view/1.xml

 

public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}

 

Then in routes.php file /config/routes.php add;

Router::extensions(['json', 'xml']); //ensure this is before the below line.
Router::scope('/', function (RouteBuilder $routes) {

More info from the manual:
http://book.cakephp.org/3.0/en/development/routing.html#resource-routes

Cakephp Tip #3 – Requesting JSON or XML

The newest version of Cakephp makes it even easier to make a JSON or XML request.

Add the request handler component to your controller;

public $components = array('Paginator','RequestHandler' );

create your action in your controller;
eg

public function testjson() {
$this->set('posts', $this->paginate());
$this->set('_serialize', array('posts'));
}

To access either the JSON or XML version simply append .json or .xml to the action name;

http://localhost/myapp/posts/testjson.json

http://localhost/myapp/posts/testjson.xml

Manual: