Cakephp3-form methods GET and POST

23666GET:
to set the method your form is send in cakephp3 as GET;

echo $this->Form->create(null, ['type' => 'get']);

to get the Data sent via get in controller;

$this->request->query['txtboxfromform'];

POST:

//set the method
echo $this->Form->create(null, ['type' => 'post']);

 

//get data
$this->request->data['txtboxfromform'];

Forms in cakephp3:
http://book.cakephp.org/3.0/en/views/helpers/form.html

Cakephp3-Creating custom queries

23666In your object table;

public function findArtistBy(Query $query, array $options)
{
$artist = $options['search'];

return $query->where(['artist LIKE ' => $artist])
->orwhere(['title LIKE ' => $artist])
->contain(['Mp3files'])
->order(['title' => 'DESC']);
}

In your controller method;

$options['search']=$search;
$query=$this->Mp3filesTags->find('ArtistBy',$options);

$this->Flash->success(__('Search complete'));

$this->set('results', $query);
$this->set('count',$count);

So what does it do?
It will return the results where the artist field is like eg.”U2″ and where the title is like “U2”.
It also has an order clause in there and will contain the related records set “mp3files”.

Reference:
http://book.cakephp.org/3.0/en/orm/query-builder.html

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

 

Sample AJAX Call and Response

23666This is just a quick example of how to send a reply from your controller to n AJAX request.

//you controller

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

//javascript function

<script>	
	function test(){
		$.ajax({
			type:"POST",
			url:"http://localhost/[YOURCAKEAPPNAME]/[CONTROLLERNAME]/testajax.json",
			async:true,
			success: function(response){
				//console.log('success');
				console.log(response.text);
			},
			error: function (response) {
				console.log('error');
				console.log(response.text);
			}
		});			
    }
</script>

A link to call the function;

<li><?= $this->Html->link(__('updateResult'), 'javascript:test()') ?></li>