I am trying to implement a search module by using AJAX.
There is an index.ctp file in my Items Controller and I have linked my index.ctp file of Items to my search.ctp file which is present under Pages controller as below:
<li><?= $this->Html->link(__('Search Products'),['controller'=>'Pages','action' => 'search']) ?></li>
For the search.ctp pages the URL displayed is : http://ift.tt/1de6B51
In my search.ctp file the code is as follows:
<head>
<title> Search Results</title>
<?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', array('inline' => false));?>
<script type="text/javascript">
$(document).ready(function() {
$("#Submit1").click(function () {
$.ajax({
type: 'post',
url: '/Items/searchData",
data: {
name: search
},
beforeSend: function(){
$("#resultField").html("Loading...");
},
success: function(response) {
jQuery('#resultField').val(response);
},
error: function(response, error) {
alert("Search :Error");
},
dataType: 'json',
global: false
});
});
});
</script>
</head>
<div>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Search Item') ?></legend>
<?php
echo $this->Form->input('search',['label'=>'Search']);
?>
</fieldset>
<?= $this->Form->button('Search Items',['label'=>'Submit1']); ?>
<?= $this->Form->end() ?>
</div>
<div id="resultField">
</div>
In my ItemsContoller page the searchData method is implemented like this:
class ItemsController extends AppController
{
public $helpers = ['Form', 'Html', 'Time'];
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
/**
*obtains search result for a given string.
*/
public function searchData()
{
$this->layout = 'ajax';
echo "here";
$search_data=[];
var_dump($search_data);
//$search_results = [];
if ($this->request->is('post')) {
$search_data= $this->request->data;
$search_data=implode("|",$search_data);
$search_results = $this->Items->find('all', array('conditions'=>array('Items.itemName LIKE'=>"%$search_data%")));
if(!empty($search_results)) {
$this->set(compact($search_results));
$this->set('_serialize',array('search_results'));
echo json_encode($search_results);
}
}
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['index', 'view','search','searchData']);
}
}
My issue is that the SearchData method is not being called and I am not getting any javascript errors also.How do i make sure that the method gets called on pressed after pressing the button.Is it due to the url in json?
Aucun commentaire:
Enregistrer un commentaire