I am trying to make an auto complete function in CakePHP but did not succeed. I tried the following code.
public function find() {
if ($this->request->is('ajax')) {
$this->autoRender = false;
$country_name = $this->request->data['Country']['name'];
$results = $this->Country->find('all', array(
'conditions' => array('Country.name LIKE ' => '%' . $country_name . '%'),
'recursive' => -1
));
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
echo json_encode($results);
}
}
// Form and jquery
<?php
echo $this->Form->create('Country', array('action' => 'find'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->submit();
echo $this->Form->end();
?>
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'/countries/find',
minLength:2
});
});
</script>
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
Breaks your JSON structure.
Keep in mind that autocomplete by default expects "label" and value keys in your JSON table, so all the script should do after fetching DB records is:
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['Country']['name'] , 'value' => $result['Country']['name'] );
}
echo json_encode($resultArr);
exit(); // may not be necessary, just make sure the view is not rendered
Also, I would create the URL to your datasource in the jQuery setup by
source:'<?=$this->Html->url(array("controller" => "countries","action"=> "find")); ?>',
And try to comment-out (just to make sure if the condition is not met by the request when autocomplete makes its call)
if ($this->request->is('ajax')) {
condition
Related
Im trying few hours repair my code but its always fail.
I have array in file:
$liquidyLista7 = array(
'Arbuz' => array(
'Wyraźny arbuz, soczysty arbuz, naprawde chyba najlepszy z oferty',
'Delikatny arbuz.',
'odświeżajacy arbuz',
'Bardzo delikatny, mniej wyrażny arbuz'
),
// and much more...
... i want to echo all values from each arrays but my "bad epic" code not work :/
function pokazOpisyVolish($liquidyLista7)
{
$i = 0;
$select = '<div id="volishPage'.$i.'" class="tab-pane fade"><ul class="comment-list">';
foreach($liquidyLista7 as $key => $record) {
$i++;
if (is_array($record)) {
$select .= '<li><p class="desc">'.$key.'</p>';
$select .= pokazOpisyVolish($record);
$select .= '</li>';
} else {
$select .= '<li><p class="desc">'.$record.'</p></li>';
}
}
$select .= '</ul></div>';
return $select;
echo pokazOpisyVolish($liquidyLista7);
Pls visit my test website and check how it works in "Mr Jack" (simple HTML - not PHP) but in "Volish" is my PHP code... :(
may be you are looking for some thing like this. the link you gave
uses plugin and css to display the result onto the webpage,
i can show you how to do it, but after that you have use your own css to display the result, i am thinking you might have add some div
name
just run this code in separate file, and you are good, understand what's happening and than add the div
<?php
$liquidyLista7 = array(
'Arbuz' => array(
'Wyraźny arbuz, soczysty arbuz, naprawde chyba najlepszy z oferty',
'Delikatny arbuz.',
'odświeżajacy arbuz',
'Bardzo delikatny, mniej wyrażny arbuz'
),
'newArtist' => array(
'Wyraźny arbuz, soczysty arbuz, naprawde chyba najlepszy z oferty',
'Delikatny arbuz.',
'odświeżajacy arbuz',
'Bardzo delikatny, mniej wyrażny arbuz'
)
);
//get the link from url
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
foreach ($liquidyLista7 as $key => $record) {
//ad artist name to the current url
echo "<a href=$actual_link?artistName=$key>$key</a><br>";
if(isset($_GET['artistName'])){
if(is_array($record)){
echo "<ul>";
foreach($liquidyLista7[$key] as $value)
if($_GET['artistName']==$key)
echo "<li>$value</li>";
}
echo "</ul>";
}
}
?>
I had created two database tables as,
Country
State
In Country table i had countryid & cname field. In State table i had state_id, state_name & country_cid.
Now i need to make a dependent dropdown i.e. when i select country dropdown box, then the particular state for that country should be displayed. I had done below coding. But it displays only country and not displays state.
This is in views/sample/register.php file.
<div class="row">
<?php echo $form->labelEx($model,'countryid');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('SampleController/dynamicSubcategory'),
array('coountry_id'=>'js:this.value'),
'dataType' => 'JSON',
'success'=>'js:function(data)'
. '{'
. 'var html="<option value=>-----Select city-----</option>";'
. '$.each(data,function(i,obj)'
. '{'
. 'html+="<option value=\'"+obj.id+"\'>"+obj.name+"</option>";'
. '});'
. '$("#state_id").html(html);'
. '}'
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_id','', array());
echo $form->error($model,'state_id'); ?>
</div>
This is in controllers/SampleController.php file
public function actiondynamicSubcategory()
{
$countryId=$_POST['coountry_id'];
$criteria=new CDbCriteria();
$criteria->select=array('state_id,state_name');
$criteria->condition='country_cid='.$countryId;
$criteria->order='state_name';
$cityAry= State::model()->findAll($criteria);
$ary=array();
foreach($cityAry as $i=>$obj)
{
$ary[$i]['state_id']=$obj->id;
$ary[$i]['state_name']=$obj->name;
}
echo json_encode($ary);
}
I had created Country model & State model. I had analyzed many sites. But i can't get right. Please anybody help.
You can try below code which I have used in one of my projects -
**Code in the view file :**
<?php $arrOptionsCountry = array('prompt'=>'Select Country','ajax'=> array('type'=>'POST','url' => ApplicationConfig::getURL('', 'site','SearchValueStates'),'update'=>'#Airports_state','beforeSend'=>'stateLoading'));
echo $form->dropDownList($model,'country',$arrCountryList,$arrOptionsCountry,array('class'=>'span11 customDropdown1_select'));
$arrOptionsState = array('prompt'=>'Select State','ajax'=> array('type'=>'POST','url' => ApplicationConfig::getURL('', 'site', 'SearchValueCities'),'update'=>'#station_name','beforeSend'=>'cityLoading'));
echo $form->dropDownList($model,'state',$arrStatesList,$arrOptionsState);
echo $form->dropDownList($model,'city',$arrCityList);
?>
**Site Controller :**
public function actionSearchValueStates()
{
$arrParam =array();
if(isset($_POST['Airports']['country']))
{
$Term = $_POST['Airports']['country'] ;
$case = "STATE-LIST";
$prompt = "Select State";
$arrParam['id'] = isset($Term)?$Term:null ;
$data = States::getList($case,$arrParam);
$data = CHtml::listData($data,'id','name');
echo CHtml::tag('option',array('value'=>''),$prompt,true);
foreach($data as $value=>$name)
{
echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
}
}
Yii::app()->end();
}
I got the answer for my question.
This is in views/sample/register.php file
<div class="row">
<?php echo $form->labelEx($model,'country');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('Sample/dynamicSubcategory'),
'update'=>'#state_name',
'data'=>array('country_id'=>'js:this.value'),
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_name','', array(), array(
'prompt'=>'Select State'
));
echo $form->error($model,'state_id'); ?>
</div>
This is in controllers/SampleController.php file
public function actiondynamicSubcategory()
{
$data=State::model()->findAll('country_cid=:countryid',
array(':countryid'=>(int) $_POST['country_id']));
$data=CHtml::listData($data,'state_id','state_name');
echo "<option value=''>Select State</option>";
foreach($data as $value=>$state_name)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($state_name),true);
}
This code works fine for dependent dropdown in yii
I have a view in my site that has two divs. one houses a search box and the other is where the result of the search is shown. by default, nothing is loaded on the result div. only when there is a search via post request, the result div is populated. However, this is causing problem with the pagination functionality as the second time the page loads, it doesnt have the data to go around with listing the rest of the results. How can i modify my controller/view to meet this need?
My action in the controller:
public function search(){
if($this->request->is('post')){
if($this->request->data['User']['search']!=null){
$search_name=$this->request->data['User']['search'];
$this->Paginator->settings = array(
'conditions'=>array('User.name LIKE'=>'%'.$search_name.'%'),
'order' => array('User.datetime' => 'desc'),
'limit' => 10
);
$feed = $this->Paginator->paginate('User');
$this->set('search_result',$feed);
}
else{
$this->Session->setFlash(__("Cant make an empty search"));
return $this->redirect(array('action'=>'search'));
}
}
}
My View:
<?php
include 'header.ctp';
echo '<div id="feed">';
echo $this->Form->create(null, array('url' => array('controller' => 'users', 'action' => 'search')));
echo $this->Form->input('search');
echo $this->Form->end('Search');
echo 'search by name';
echo '</div>';
if(isset($search_result)){
echo '<div id="tweet_records">';
if(!empty($search_result)){
foreach ($search_result as $user) :
$formatted_text;
$latest_tweet_time;
$formatted_time;
if(!empty($user['Tweet'])){
$formatted_text=$this->Text->autoLinkUrls($user['Tweet']['0']['tweet']);
$latest_tweet_time=$user['Tweet']['0']['datetime'];
$formatted_time;
if(strlen($latest_tweet_time)!=0){
$formatted_time='Tweeted at '.$latest_tweet_time;
}
else{
$formatted_time='No tweets yet';
}
}
else if(empty($user['Tweet'])){
$formatted_text='No tweets yet';
$formatted_time='';
}
echo '<table id="t01">';
echo'<tr>';
echo '<td>'.
$user['User']['name'].'#'.$this->HTML->link($user['User']['username'], array('controller'=>'tweets','action'=>'profile',$user['User']['id'])).'<br>'.$formatted_text.' '.'<br>'.'<font color="blue">'.$formatted_time.'</font>';
echo '<div id="delete">';
$selector='true';
foreach ($user['Follower'] as $follower) :
if($follower['follower_user_id']==AuthComponent::user('id')){
$selector='false';
echo $this->Form->postlink('Unfollow',array('controller'=>'followers','action'=>'unfollow',$user['User']['id']),array('confirm'=>'Do you really want to unfollow this person?'));
}
endforeach;
if($selector=='true' & $user['User']['id']!=AuthComponent::user('id')){
echo $this->Form->postlink('Follow',array('controller'=>'followers','action'=>'follow',$user['User']['id']));
}
echo '</div>';
echo '</td>';
echo '</tr>';
endforeach;
echo'</table>';
echo 'Pages: ';
echo $this->Paginator->prev(
' < ',
array(),
null,
array('class' => 'prev disabled')
);
echo $this->Paginator->numbers();
echo $this->Paginator->next(
' > ' ,
array(),
null,
array('class' => 'next disabled')
);
}
else{
echo '<font color="red"> No results found </font>';
}
echo '</div>';
}
You are searching for results only on post request. But when you press the next button you are making a get request. So the first if statement doen't return true so you are not passing any data to your view.
Even if you remove the first if statement for post you'll still won't see any data because the next button doesn't post any data to make true the second statement.
PS:
On CakePHP include is not a preferable thing to do. Also you haven't mentioned the version you are using.
I am working on a custom Joomla module that returns an LDAP directory with the ability to change sort options on the front end using AJAX.
The getAjax function returns the directory just fine if I call it as a string in the default.php template file (bypassing AJAX):
echo $directoryList;
The problem is when I try to return the variable "$content" through ajax, the directory does not show when changing the selector. However, in the helper.php if I change "return $content" to "return $sortOption", AJAX works and returns the selected option for the sort. So I know AJAX is working. Also note that if I change to "return $content.$sortOption", the select option variable is shown but no directory. I think it has something to do with the LDAP not loading properly through AJAX.
Mod_nu_directory.php
// no direct access
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once( dirname(__FILE__) . '/helper.php' );
// Instantiate global document object
$doc = JFactory::getDocument();
$js = <<<JS
(function ($) {
$(document).on('change', '#sortDir select', function () {
var value = $('#sortDir option:selected').val(),
request = {
'option' : 'com_ajax',
'module' : 'nu_directory',
'data' : value,
'format' : 'raw'
};
$.ajax({
type : 'POST',
data : request,
success: function (response) {
$('.status').html(response);
}
});
return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);
$dirDepts = $params->get('dirDepts', 'All');
$dirOptions = $params->get('dirOptions');
$directoryList = modNuDirectoryHelper::getAjax($dirDepts);
require( JModuleHelper::getLayoutPath('mod_nu_directory'));
helper.php
class modNuDirectoryHelper {
public static function getAjax($dirDepts) {
//get the sort variable from the select field using ajax:
$input = JFactory::getApplication()->input;
$sortOption = $input->get('data');
//Set our variables
$baseDN = 'CN=Users,DC=site,DC=local';
$adminDN = "admin";
$adminPswd = "P#55WorD";
$ldap_conn = ldap_connect('ldaps://ad.site.local');
$dirFilter = strtolower('(|(department=*' . implode('*)(department=*', $dirDepts) . '*))');
//if "All" categories are selected, dont add a filter, else add a directory filter
(strpos($dirFilter, 'all directory') !== false) ?
$filter = '(&(objectClass=user)(|(memberof=CN=Faculty,CN=Users,DC=site,DC=local)(memberof=CN=Staff,CN=Users,DC=site,DC=local)))' : $filter = '(&(objectClass=user)(|(memberof=CN=Faculty,CN=Users,DC=site,DC=local)(memberof=CN=Staff,CN=Users,DC=site,DC=local))' . $dirFilter . ')';
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
$ldap_bind = ldap_bind($ldap_conn, $adminDN, $adminPswd);
if (!$ldap_bind) {
return 'Oh no! Unable to connect to the directory :(';
} else {
$attributes = array('displayname', 'mail', 'telephonenumber', 'title', 'department', 'physicalDelivery', 'OfficeName', 'samaccountname', 'wwwhomepage', 'sn', 'givenname');
$result = ldap_search($ldap_conn, $baseDN, $filter, $attributes);
//sort the entries by last name
ldap_sort($ldap_conn, $result, $sortOption);
$entries = ldap_get_entries($ldap_conn, $result);
// let's loop throught the directory
for ($i = 0; $i < $entries["count"]; $i++) {
// define the variables for each iteration within the loop
$userName = $entries[$i]['displayname'][0];
$userTitle = $entries[$i]['title'][0];
$userDept = $entries[$i]['department'][0];
$userPhone = '888-888-8888, ext. ' . $entries[$i]['telephonenumber'][0];
$userOffice = 'Office: ' . $entries[$i]['physicaldeliveryofficename'][0];
//person must have a name, title, and department
if ((!empty($userName)) || (!empty($userTitle)) || (!empty($userDept))) {
$content .= $userName . '<br />'
. $userTitle . '<br />'
. $userDept . '<br />'
. (!empty($userPhone) ? $userPhone : '') . '<br />'
. (!empty($userOffice) ? $userOffice : '') . '<br />'
. '<br />';
}
}
}
return $content;
}
}
default.php
<?php
// No direct access
defined('_JEXEC') or die;
?>
<p>Displaying the following departments:<br />
<?php
foreach ($dirDepts as $dirDept) {
echo '[' . $dirDept . '] ';
}
?>
</p>
<p class="dirOptions">Displaying the following Options:<br />
<?php
foreach ($dirOptions as $dirOption) {
echo '[' . $dirOption . '] ';
}
?>
</p>
<?php
if (in_array('showSort', $dirOptions)) {
?>
<form method="post" id="sortDir">
<select name="sortDir" >
<option value="displayname" selected="selected">First name</option>
<option value="sn">Last name</option>
<option value="department">Department</option>
</select>
</form>
<?php } ?>
<div class="status"></div>
The problem was the $entries array was not being treated as an actual array. I've tested this by substituting the $entry array with a static array and the AJAX callback behaved properly. I since removed the ajax functionality and just echoed the function and works fine. This is not solve why AJAX can't pull the array though.
Here's my problem: I have two select fields in my web application.
The second one depends on the choice made on the first one. The first one is populated from my database with the classical:
<?php
//connection to database in an include file
$query = "SELECT DISTINCT platform
FROM Appversions";
$res = mysql_query($query);
while($row = mysql_fetch_array($res)) {
echo "<option value=\"\"" . $row['platform'] . "</option>\n";
}
?>
which is working just fine.
But then I need to populate my second select with a query that would look like:
SELECT version
FROM Appversions
WHERE platform = <choice made in first select>;
I understand that I need to use JavaScript with an onChange function call to do that, but I can't figure out what that function should look like or how it will have access to my query result.
Usually i have this jquery code:
$('#select1').change(function(){
if($(this).val() == ''){
$('#select2').attr('disabled', 'true');
}else{
var select1 = $(this).val();
$.getJSON('index.php',
{
option: "com_spin",
controller: "guest",
task: "getProvincieByRegionId",
idRegione: idRegione
},
function(json){
$('#select2').html(json.html);
}
);
$('#select2').removeAttr('disabled');
}
});
in php i have something like this (basically i return the html for the options:
Zend_Loader::loadClass ( 'Zend_Json' );
$idRegione = JRequest::getVar ( "idRegione" );
$modelProvince = new Spin_lkpprovincia ();
$provincie = $modelProvince->getElencoProvinciePerRegione ( $idRegione );
$html = "<option value=''>Selezionare una voce</option>";
foreach ( $provincie as $provincia ) {
$html .= "<option value='" . $provincia ['idProvincia'] . "'>" . $provincia ['nome'] . "</option>";
}
$json = array (
success => "OK",
html => $html );
$json = Zend_Json::encode ( $json );
echo $json;
die ();