AJAX in cake 3.6 - Error: Controller actions can only return Cake\Http\Response or null


#1

I have some problem using ajax, please help me .

my controller action is :-

public function getBlocksByDistrict(){

	$this -> autoRender = false;  
	
	$arr = array();
	if($this->request->is('ajax')){
		$id = $this->request->getQuery('id'); //echo $id;die;
		$this->loadModel('BlockCity');
		
		$blockCityData = TableRegistry::getTableLocator()->get('BlockCities')->find('all', array('fields'=>array('BlockCities.rgi_block_code','BlockCities.name'), 'conditions'=>array('BlockCities.rgi_district_code='."'".$id."'"), 'recursive'=>-1));
		$obj_to_array_blockCityData = $blockCityData->toArray();
		
		$blocks = array();
		foreach($obj_to_array_blockCityData as $key => $value){
			$blocks[$value['rgi_block_code']] = $value['name'];
		}
		//echo "<pre>";print_r(json_encode($blocks));die;
		
		return json_encode($blocks);
		//$this->set(compact('blocks'));
        //$this->set('_serialize', ['blocks']);
	}
}

and JS function in ctp file :-

(document).ready(function(){ (’#TransactionRgiDistrictCode’).change(function(){
var url = (this).attr('rel'); //alert(url);return false; var dist_id = (’#TransactionRgiDistrictCode’).val();

	$.ajax({
		type: 'GET',
		url: url,
		data: ({id : dist_id}),
		beforeSend: function(xhr) 
		{
			xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		},
		success: function(response) 
		{	
			if (response) 
			{ 
				//alert(response);
				console.log("content = " + response);
				return false;
				var result = JSON.parse(response); 
				$.each(result, function(val, text) {
					$('#TransactionRgiBlockCode').append(
						$('<option></option>').val(val).html(text)
					);  
				});	
			}
		},
		error: function(e) 
		{
			alert("An error occurred: " + e.responseText.message);
			console.log(e);
		}
	});
});

});

I have followed the below url with the sandbox url as well.
http://www.dereuromark.de/2014/01/09/ajax-and-cakephp/

please help me where I am mistaking.

I will be really very thankful for this. Please help will be appreciated.


#2

Hello,

Try to return your response in your controller like this :

$this->response->body(json_encode($blocks));

return $this->response;


#3

Hello christ57,

Thanks for your reply. It works. Thanks a lot.