i`m making a search for products on the site. When you load the page the first time, you see all the products.
The product block is wrapped in pjax and pagination is carried out by the widget LinkPager.
A search request to the server is carried out through ajax, and a block of products found returns via renderPartial. If I try to switch to the next page, search results are reset and you see all the products again. It turns out that the widget LinkPager doesn’t work properly after carrying out of renderPartital.
view:
<div class="search-wrap">
<input type="text" class="search-input" id="search" placeholder="Поиск по названию" name="p">
<button type="submit" class="btn filter-search-btn-menu" id="btns">Поиск</button>
<script>
$('#btns').on('click', function(e){
var search = $('#search').val();
$.ajax({
type: 'POST',
url: "/person/notice",
data: { 'search': search },
cache: false,
success: function (data) {
$('#allnotice').html(data);
});
});
</script>
</div>
<div id="allnotice">
<?php yii\widgets\Pjax::begin();?>
<div id="up">
<?php if ($offerings) foreach($offerings as $one): ?>
<div class="preview-notice-wrap">
<div class="preview-notice-inner">
<h4><?php echo $one->title; ?></h4>
<div class="preview-notice">
<div>
<p><?php
$price = $one->start_price;
echo number_format($price) . ' ₽';
?></p>
</div>
<div>
<p><?php
$date = $one->created;
echo Yii::$app->formatter->asDate($date, 'd MMMM y');
?> </p>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<div class="notice-pagination-wrap preview-notice-pagination">
<?= \app\components\MyPager::widget([
'pagination' => $pages,
'maxButtonCount' =>7,
'prevPageLabel' => false,
'nextPageLabel' => false,
'activePageCssClass' => ['class' => 'page-active'],
'options' => ['class' => 'page-test'],
'linkOptions' => ['class' => 'page-link'],
]); ?>
</div>
</div>
<?php yii\widgets\Pjax::end(); ?>
</div>
controller:
public function actionNotice()
{
$user_id = Yii::$app->user->id;
$user = Person::findOne($user_id);
if (Yii::$app->request->isPost && Yii::$app->request->isAjax && Yii::$app->request->post()){
$s = \Yii::$app->request->post('search');
$count = \app\models\Offering::find()->where(['person_id' => $user->id])->andWhere(['like', 'title', $s])->count();
$query = \app\models\Offering::find()->where(['person_id' => $user->id])->andWhere(['like', 'title', $s])->orderBy('id DESC');
$pages = new \yii\data\Pagination(['totalCount' => $query->count(),'pageSize' => 4, 'pageParam' => 'page-top']);
$offerings = $query->offset($pages->offset)->limit($pages->limit)->all();
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $this->renderPartial('_notice, ['count' => $count, 'pages' => $pages, 'offerings' => $offerings]);
}
$count = \app\models\Offering::find()->where(['person_id' => $user->id])->count();
$query = \app\models\Offering::find()->where(['person_id' => $user->id])->orderBy('id DESC');
$pages = new \yii\data\Pagination(['totalCount' => $query->count(),'pageSize' => 4, 'pageParam' => 'page-top']);
$offerings = $query->offset($pages->offset)->limit($pages->limit)->all();
return $this->render('notice', ['count' => $count, 'pages' => $pages, 'offerings' => $offerings]);
}
I have one solution:
url: "/person/notice?search="+search,
put value in url.
$('#btns').on('click', function(e){
var search = $('#search').val();
$.ajax({
type: 'POST',
url: "/person/notice?search="+search,
data: { 'search': search },
cache: false,
success: function (data) {
$('#allnotice').html(data);
});
});
and you can catch it in controller
if(isset($_POST['search']))
$search_word = trim($_POST['search']);
if(isset($_GET['search']))
$search_word = trim($_GET['search']);
Related
I am new to ajax, so I am learning, and I am stuck and have tried to search everywhere for what I need to no avail. I have a dropdown with a list of locations. However based on another dropdown I want to return a default location to the list. So if I pick asset A, its default location will autopopulate in the dropdown but still give me alternatives via the $locations list to choose another location. I can return the correct data to the div but I don't know how to populate it in a dropdown. Below is what I have that populates the div. Any help on how I would send it to the dropdown with the $locations list still intact but this value as the default selected would be appreciated.
Dropdowns
<div class="form-group">
<label class="control-label" for="asset_id" id="asset_id" >
Asset
</label>
<?php
echo $this->Form->input( 'WorkorderAsset.0.asset_id', array(
'type'=>'select',
'data-placeholder'=>'Select An Asset Type From Above...',
'class'=>'chzn-select form-control asset',
'empty' => true,
'id'=>'asset',
'label'=>false,
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation text-
danger"></i></div></div>',
'between' => '<div class="input-group">',
));
?>
</div>
<div class="row">
<div class="col-md-6">
<?php
echo $this->Form->input( 'location_id', array(
'id'=> 'location',
'options'=>$locations,
'class'=>'chzn-select form-control',
'empty' => true,
'z'=>'Select A Location',
'required'=>false,
'between' => '<div class="input-group">',
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation text-
danger"></i></div></div>',
));
?>
<div class="row">
<div class="col-md-6">
$('#asset').on('change', function() {
var id = $('#asset').val();
if (id != "") {
$.ajax({
type: 'POST',
url: '/workorders/workorders/getInfo/'+ id +'.json',
dataType: 'html',
beforeSend: function(xhr) {
$(".overlay").show();
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function( response ) {
console.log(response);
$('#location').html(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
complete: function() {
$(".overlay").hide();
},
});
}
else {
alert("Please select an asset");
}
});
In my controller
public function getInfo($id=null)
{
$locate = $this->request->data = $this->Asset->find('first', array(
'conditions'=>array(
'Asset.id' => $id
),
'contain'=>array(
'Location'=>array(
'fields'=>array('Location.name')
),
)
));
if ($this->request->is('ajax')) {
$this->set( 'locate', $locate);
}
}
In my JSON
<?php
$location = (!empty($locate['Location']['name'])) ? $locate['Location']['name'] : ' ';
?>
<div >
<? echo "Default Asset Location:" . " " . $location ?>
</div>
I figured it out. The answer is as follows.
View:
<div class="form-group">
<label class="control-label" for="asset_id" id="asset_id" >
Asset
</label>
<?php
echo $this->Form->input( 'WorkorderAsset.0.asset_id', array(
'type'=>'select',
'data-placeholder'=>'Select An Asset Type From Above...',
'class'=>'chzn-select form-control asset',
'empty' => true,
'id'=>'asset',
'label'=>false,
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation
text-
danger"></i></div></div>',
'between' => '<div class="input-group">',
));
?>
</div>
<div class="row">
<div class="col-md-6">
<?php
echo $this->Form->input( 'location_id', array(
'id'=> 'location',
'options'=>$locations,
'class'=>'chzn-select form-control',
'empty' => true,
'z'=>'Select A Location',
'required'=>false,
'between' => '<div class="input-group">',
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation
text-
danger"></i></div></div>',
));
?>
<div class="row">
<div class="col-md-6">
$('#asset').on('change', function() {
var id = $('#asset').val();
if (id != "") {
$.ajax({
type: 'POST',
url: '/workorders/workorders/getInfo/'+ id +'.json',
dataType: 'html',
success: function( response ) {
console.log(response);
$("#location").attr("data-placeholder", response);
$('#location' ).val('').trigger( 'chosen:updated' );
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
complete: function() {
$(".overlay").hide();
},
});
}
else {
}
});
Controller:
public function getInfo($id=null)
{
if (!$id) {
throw new NotFoundException();
}
$locate = $this->Asset->find('first', array(
'conditions'=>array(
'Asset.id'=>$id
),
'contain'=>array(
'Location'=>array(
'fields'=>array(
'Location.id',
'Location.name',
),
'order'=>array('Location.name'=> 'asc')
)
)
));
#pr($groupSelection);
#exit;
$this->set(compact('locate'));
}
JSON
<?php
if (!empty($locate['Location'])) {
echo '<option value="' . $locate['Location']['id'] . '">' . $locate['Location']
['name'] . '</option>';
}
else {
echo '<option value="">' . __('No Options Available') . '</option>';
}
?>
I have a Wordpress website hosted on 20i. I'm almost certain that everything worked fine until I pointed the a records to get the website off its test domain and onto the actual one, this might be unrelated but I figured I'd mention it incase. Anyway for some reason my Ajax function works fine on desktop but not on mobile. When I look at it on mobile none of the posts are visible and if I select a filter nothing happens. Does anyone know what this could be? I've looked around for answers but I can't seem to find the solution.
Here's my code;
jQuery
// submit form function
jQuery('#form').on('submit', function(e){
e.preventDefault();
var $ = jQuery;
var filter = $('#form');
var form_data = $('#form').serializeArray();
$('#load_more').data('page', 1);
$.ajax({
url: ajax_url,
type: 'post',
data: form_data,
dataType: 'json',
error : function(response){
console.log(response);
},
success : function(response){
$('#loop').empty();
for( var i = 0; i < response.post_cont.length; i++ ){
var html =''+
'<div class="col-12 col-md-4 column">'+
'<a href="'+ response.post_cont[i].permalink +'">'+
'<div class="card" style="width: 100%;">'+
'<div class="post_image" style="background-image: url('+ response.post_cont[i].image +');"></div>'+
'<div class="card-body">'+
'<h5 class="card-title">'+ response.post_cont[i].title +'</h5>'+
'</div>'+
'</div>'+
'</a>'+
'</div>';
$('#loop').append(html);
}
}
});
});
php AJAX function
<?php
add_action('wp_ajax_nopriv_filter', 'filter');
add_action('wp_ajax_filter', 'filter');
// this function runs after it is called inside our_work_ajax.js
function filter(){
if( $_POST['type'] && !empty($_POST['type']) ){
$category = $_POST['type'];
}else{
$category = array( 'Assisted Needs/Residential', 'Commercial/Educational', 'Private Housing', 'Social-Housing' );
}
$args = array(
'post_type' => 'our_work',
'posts_per_page' => 9,
'orderby' => 'date',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $category
)
)
);
$query = new WP_Query( $args );
$no_of_posts = $query->found_posts;
if( $query->have_posts() ):
while( $query->have_posts() ): $query->the_post();
$main_field = get_field('Images');
$first_row = $main_field[0];
$img = $first_row['Image'];
$imgsize = $img['sizes']['large'];
// creating an array of content needed from array
$post_cont[] = array(
"permalink" => get_the_permalink(),
"image" => $imgsize,
"title" => get_the_title(),
);
endwhile;
endif;
// array getting the total number of posts
$max_posts[] = array(
"no_of_posts" => $no_of_posts
);
// converting arrays into json and submitting it to the ajax_url for the .js file
echo json_encode(array( "post_cont" => $post_cont, "max_posts" => $max_posts));
wp_reset_postdata();
die();
}
?>
HTML
<form action="" method="POST" id="form">
<div id="filters">
<div class="option">
<p>Assisted Needs/Residential</p>
<input type="checkbox" name="type[]" value="Assisted Needs/Residential">
</div>
<div class="option">
<p>Commercial/Educational</p>
<input type="checkbox" name="type[]" value="Commercial/Educational">
</div>
<div class="option">
<p>Private Housing</p>
<input type="checkbox" name="type[]" value="Private Housing">
</div>
<div class="option">
<p>Social Housing</p>
<input type="checkbox" name="type[]" value="Social Housing">
</div>
</div>
<input type="hidden" name="action" value="filter">
</form>
<div id="loop" class="row">
</div>
<script>
jQuery(document).ready(function($){
var inputs = $('#form .option input');
inputs.each(function(){
if( $(this).is(':checked') ){
$(this).parent().addClass('active');
}
});
$('#form').submit();
});
</script>
AJAX url inside functions.php
wp_localize_script( 'all_js', 'ajax_url', admin_url('admin-ajax.php') );
I am in the learning stage in php.Please help me with my update form.Advanced thanks. I have a form to update any user information with a button "Save" and "Reset" button.I update any information the version number increase.But the problem is when i do not update any information and click on "Save" button the version number increases.It should not increase.I am giving my Controller and form code....
public function actionCreate()
{
$model=new CvUpload;
$model2=new CvUpload;
$UserType=new UserType;
$CvHistory=new CvHistory;
$this->performAjaxValidation($model);
if(!empty($_POST))
{
$id = $_POST['CvUpload']['user_id'];
$cv_type = $_POST['CvUpload']['cv_type'];
$criteria = new CDbCriteria();
$criteria->condition = "user_id = $id AND is_current='yes' AND cv_type='$cv_type'";
$CvUploadmodel = CvUpload::model()->find($criteria);
if(!empty($CvUploadmodel))
{
$CvUploadmodel->is_current='no';
$CvUploadmodel->status='inactive';
if($CvUploadmodel->save(false)){
$model->attributes=$_POST['CvUpload'];
$model->upload_date = new CDbExpression("NOW()");
$model->update_date = new CDbExpression("NOW()");
$model->version_id = $CvUploadmodel->version_id+1;
if($model->save(false))
{
$CvHistory->cv_id = $model->cv_id;
$CvHistory->user_id = $model->user_id;
$CvHistory->job_title_id = $model->job_title_id;
$CvHistory->cv_type = $model->cv_type;
$CvHistory->version_id = $model->version_id;
$CvHistory->file_name = $model->file_name;
$CvHistory->upload_date = $model->upload_date;
$CvHistory->update_date = $model->update_date;
$CvHistory->is_current = $model->is_current;
$CvHistory->status = $model->status;
if($CvHistory->save(false))
{
$this->redirect(array('view','id'=>$model->cv_id));
}
}
}
}
else
{
$model->attributes=$_POST['CvUpload'];
$model->upload_date = new CDbExpression("NOW()");
$model->update_date = new CDbExpression("NOW()");
$model->version_id=1;
if($model->save())
{
$CvHistory->cv_id = $model->cv_id;
$CvHistory->user_id = $model->user_id;
$CvHistory->job_title_id = $model->job_title_id;
$CvHistory->cv_type = $model->cv_type;
$CvHistory->version_id = $model->version_id;
$CvHistory->file_name = $model->file_name;
$CvHistory->upload_date = $model->upload_date;
$CvHistory->update_date = $model->update_date;
$CvHistory->is_current = $model->is_current;
$CvHistory->status = $model->status;
if($CvHistory->save(false))
{
$this->redirect(array('view','id'=>$model->cv_id));
}
}
}
}
$this->render('create',array(
'model'=>$model,
'UserType'=>$UserType,
'CvHistory'=>$CvHistory,
));
}
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$CvHistory=new CvHistory;
if(isset($_POST['CvUpload']))
{
$model->attributes=$_POST['CvUpload'];
if($model->save())
{
$criteria = new CDbCriteria();
$criteria->condition = "cv_id = $model->cv_id AND is_current = 'yes'";
$CvHistory = CvHistory::model()->find($criteria);
$CvHistory->is_current = 'no';
$CvHistory->status = 'inactive';
if($CvHistory->save(false))
{
$new_CvHistory=new CvHistory;
$new_CvHistory->cv_id = $model->cv_id;
$new_CvHistory->user_id = $model->user_id;
$new_CvHistory->job_title_id = $model->job_title_id;
$new_CvHistory->cv_type = $model->cv_type;
$new_CvHistory->version_id = $CvHistory->version_id+1;
$model->version_id = $new_CvHistory->version_id ;
$new_CvHistory->file_name = $model->file_name;
$new_CvHistory->upload_date = $model->upload_date;
$new_CvHistory->update_date = new CDbExpression("NOW()");
$model->update_date = $new_CvHistory->update_date ;
$new_CvHistory->status = $model->status;
$new_CvHistory->is_current = "yes";
$new_CvHistory->save(false);
$model->save(false);
if($new_CvHistory->save(false))$this->redirect(array('view','id'=>$model->cv_id));
}
}
}
$this->render('update',array(
'model'=>$model,
'CvHistory'=>$CvHistory,
));
}
MY form button code:
<style>
#type {
background-color:#f5f5f5;
font-family: 'Arial';
font-size: 20px;
text-decoration: none;
color:#b2b2b2;
border:none;
float: right;
}
div.form label {
display: block;
font-size: 1em;
font-weight: bold;
}
.types-add{
float: right;
}
#type:hover {
border: none;
}
</style>
<?php if (Yii::app()->user->hasFlash('created')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('created'); ?>
</div>
<?php endif; ?>
<div class="form">
<?php $form=$this->beginWidget(
'booster.widgets.TbActiveForm',
array(
'id'=>'CvUpload-form',
'type' => 'horizontal',
'htmlOptions' => array(
'class' => 'well',
'enctype' => 'multipart/form-data',
)
));
?>
<fieldset>
<h1 align="center">CV Upload</h1>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php
$criteria=new CDbCriteria();
echo $form->dropDownListGroup(
$model,
'user_id',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => CHtml::listData(User::model()->findAll($criteria), 'id', 'user_id'),
'dataProvider'=>$model->searchByUserId(Yii::app()->user->getId()),
'htmlOptions' => array('prompt'=>'Select'),
)
)
); ?>
</div>
<div class="row" id="jobTitle">
<?php
$criteria = new CDbCriteria;
$criteria->condition = "status= 'active'";
echo $form->dropDownListGroup(
$model,
'job_title_id',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => CHtml::listData(JobTitle::model()->findAll($criteria), 'id', 'name'),
'htmlOptions' => array('prompt'=>'Select job title'),
)
)
); ?>
</div>
<?php echo CHtml::form($this->createUrl('uploadreport'), 'post', array('enctype'=>'multipart/form-data'));?>
<label class="col-sm-3 control-label required" for="CvUpload_file_name">
Upload File
</label>
<div class="row" id="file_upload" style="margin-left:20%; margin-bottom:2%;">
<?php
$this->widget('CMultiFileUpload',array(
'name' => 'files',
'accept' => 'doc|docx|pdf',
'max' => 1,
'htmlOptions' => array('size' => 25),
));
echo CHtml::htmlButton('Upload',array(
'onclick'=>'javascript: send();', // on submit call JS send() function
'id'=> 'post-submit-btn', // button id 'newcreate'
'class'=>'btn btn-primary',
));
?>
</div>
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
<script src="http://code.jquery.com/jquery-migrate-1.2.0.js"></script>
<script>
function send(){
var formData = new FormData($("#CvUpload-form")[0]);
$.ajax({
url: '<?php echo Yii::app()->createUrl("CvUpload/upload"); ?>',
type: 'POST',
data: formData,
datatype:'json',
beforeSend: function() {
},
success: function (data) {
$("#CvUpload_file_name").val(data);
},
complete: function() {
},
error: function (data) {
alert("There may a error on uploading. Try again later");
},
cache: false,
contentType: false,
processData: false
});
return false;
}
</script>
<div class="row" id="file_name">
<?php echo $form->textFieldGroup(
$model,'file_name',
array(
'wrapperHtmlOptions' => array(
'class'=> 'col-sm-5',
),
)
);
?>
</div>
<div class="row" id="statustype">
<?php
$status = array('active'=>'Active', 'inactive'=>'Inactive');
echo $form->dropDownListGroup(
$model,
'status',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => $status,
'htmlOptions' => array('prompt'=>'Select a status'),
)
)
); ?>
</div>
<div class="row" id="statustype">
<?php
$is_current = array('yes'=>'Yes', 'no'=>'No');
echo $form->dropDownListGroup(
$model,
'is_current',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => $is_current,
'htmlOptions' => array('prompt'=>'Select a status'),
)
)
); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',array(
'class'=>'btn btn-primary',
'style'=>"position:relative; margin-left:25%",
'id'=> 'yt1', // button id
)); ?>
</div>
</fieldset>
<?php $this->endWidget(); ?>
</div><!-- form -->
<!--/*/*
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'cv-upload-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'user_id'); ?>
<?php echo $form->textField($model,'user_id',array('size'=>20,'maxlength'=>20)); ?>
<?php echo $form->error($model,'user_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'upload_date');enter code here ?>
<?php echo $form->textField($model,'upload_date'); ?>
<?php echo $form->error($model,'upload_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'file_name'); ?>
<?php echo $form->textField($model,'file_name',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'file_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'file_location'); ?>
<?php echo $form->textField($model,'file_location',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'file_location'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
If you don't change form values, it doesn't mean that this data wouldn't be sended to server.
Here at least button save will sended, so this case will always true:
if(!empty($_POST))
You didn't show whole form, but I suggest that fields user_id and cv_type has values (no mater values where changed or not, if form has fields they will be submited)
$id = $_POST['CvUpload']['user_id'];
$cv_type = $_POST['CvUpload']['cv_type'];
That's why model $CvUploadmodel = CvUpload::model()->find($criteria); loads and increament version_id
i am trying this sample about Creating a dependent dropdown i created form in provinceCity/_form and copy actionDynamiccities to ProvinceCityController.php but when i change dropDown list i have not any change ?
i think i must to enable ajax but i do not how i do it?
<?php echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('ProvinceController/dynamiccities'), //url to call.
//Style: CController::createUrl('ProvinceCity/methodToCall')
'update'=>'#city_id', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
)));
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array()); ?>
Here is what you will do in _form
<?php echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('ProvinceController/dynamiccities'), //url to call.
'update'=>'#city_name', //selector to update
'data'=>array('country_id' => 'js:this.value'),
)));
?>
</div>
<div id=city_name>
<?php echo $form->dropDownList($model, 'city_id', array()); ?>
</div>
Hopefully, it would help you.
It should be,
<?php
$countryAry=array(1=>'USA',2=>'France',3=>'Japan');
echo CHtml::dropDownList('country_id','', $countryAry,
array
(
'ajax' => array
(
'type'=>'POST',
'url'=>CController::createUrl('Controller/action'),
'dataType'=>'JSON',
'success'=>'js:function(data)'
. '{'
. ' var opt="<option value=>-----Select city-----</option>";'
. ' $.each(data,function(i,obj)'
. ' {'
. ' opt+="<option value=\'"+obj.id+"\'>"+obj.name+"</option>";'
. ' });'
. ' $("#city_id").html(opt);'
. '}'
)
));
echo CHtml::dropDownList('city_id','', array());
?>
But, I suggest you to implement this task as showing bellow.
<?php
$countryAry=array(1=>'USA',2=>'France',3=>'Japan');
echo CHtml::dropDownList('country_id','', $countryAry,array('onchange'=>'js:getCities()'));
echo CHtml::dropDownList('city_id','', array());
?>
<script type="text/javascript">
function getCities()
{
$.ajax
({
type:'POST',
url:'Controller/action',
dataType:'JSON',
success:function(data)
{
var opt="<option value=>-----Select city-----</option>";
$.each(data,function(i,obj)
{
opt+="<option value='"+obj.id+"'>"+obj.name+"</option>";
});
$("#city_id").html(opt);
}
});
}
</script>
I found the solution here Dependent dropdown list in yii
<?php
$model=new ModelClass; // initilize it in controller
$form=$this->beginWidget('CActiveForm', array(
'id'=>'dependent-form',
'enableClientValidation'=>true,
'htmlOptions' => array('enctype' => 'multipart/form-data','autocomplete'=>'off'),
'clientOptions'=>array(
'validateOnSubmit'=>true,
)
));
?>
<div class="row">
<?php
echo $form->dropDownList($model,'country_id',
CHtml::listData(Countries::model()->findAll(), 'id', 'title'),
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('YourController/loadstates'), // get states list
'update'=>'#ModelClass_state_id', // add the state dropdown id
'data'=>array('country_id'=>'js:this.value'),
)));
?>
</div>
<div class="row">
<?php
echo $form->dropDownList($model,'state_id',
array(),
array(
'prompt'=>'Select State',
'ajax' => array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('YourController/loadcities'), // get states list
'update'=>'#ModelClass_city_id', // add the state dropdown id
'data'=>array('state_id'=>'js:this.value'),
)));
?>
</div>
<div class="row">
<?php
echo $form->dropDownList($model,'city_id',array(),array('empty'=>'-choose city-'));
?>
</div>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Add' : 'Update',array('class'=>'btn btn-primary')); ?>
<?php $this->endWidget(); ?>
My form will validate on the client side but I'm trying to figure out why its not validating on the server side. I don't have my php complete but its not even bringing up the POST request in my console saying its submitting the form to the server.
jQuery:
$(document).ready(function()
{
/*
* Validate the form when it is submitted
*/
var validateform = $("#newArticleForm").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted.'
: 'You missed ' + errors + ' fields. They have been highlighted.';
$('.box .content').removeAlertBoxes();
$('.box .content').alertBox(message, {type: 'warning', icon: true, noMargin: false});
$('.box .content .alert').css({
width: '100%',
margin: '0',
borderLeft: 'none',
borderRight: 'none',
borderRadius: 0
});
} else {
$('.box .content').removeAlertBoxes();
}
},
showErrors : function(errorMap, errorList) {
this.defaultShowErrors();
var self = this;
$.each(errorList, function() {
var $input = $(this.element);
var $label = $input.parent().find('label.error').hide();
$label.addClass('red');
$label.css('width', '');
$input.trigger('labeled');
$label.fadeIn();
});
},
submitHandler: function(form) {
var dataString = $('#newArticleForm').serialize();
$.ajax({
type: 'POST',
url: '/kowmanager/dashboard/articleSubmit',
data: dataString,
dataType: 'json',
success: function(data) {
if (data.error) {
$('.box .content').removeAlertBoxes();
$('.box .content').alertBox(data.message, {type: 'warning', icon: true, noMargin: false});
$('.box .content .alert').css({
width: '',
margin: '0',
borderLeft: 'none',
borderRight: 'none',
borderRadius: 0
});
}
else
{
$('.box .content').removeAlertBoxes();
$('.box .content').alertBox(data.message, {type: 'success', icon: true, noMargin: false});
$('.box .content .alert').css({
width: '',
margin: '0',
borderLeft: 'none',
borderRight: 'none',
borderRadius: 0
});
$(':input','#newArticleForm')
.not(':submit, :button, :hidden, :reset')
.val('');
}
}
});
}
});
});
Controller:
function articleSubmit()
{
$outputArray = array('error' => 'yes', 'message' => 'unproccessed');
$outputMsg = '';
// Sets validation rules for the login form
$this->form_validation->set_rules('title', 'Title',
'trim|required|xss_clean|alpha_numeric');
$this->form_validation->set_rules('category', 'Category',
'integer');
$this->form_validation->set_rules('isSticky', 'Is Sticky',
'integer');
$this->form_validation->set_rules('comments', 'Allow Comments',
'integer');
// Checks to see if login form was submitted properly
if (!$this->form_validation->run())
{
$outputArray['message'] =
'There was a problem submitting the form! Please refresh the window and try again!';
}
else
{
}
}
View:
<?php $attributes = array('class' => 'validate', 'id' => 'newArticleForm'); ?>
<?php echo form_open_multipart('', $attributes) ?>
<div class="content no-padding">
<div class="section _100">
<?php echo form_label('Title', 'title'); ?>
<div>
<?php echo form_input('title', '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Category', 'category'); ?>
<div>
<?php echo form_dropdown('category', $categories, '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Is Sticky', 'sticky'); ?>
<div>
<?php
$options = array(
'' => 'Please Select An Option',
'0' => 'No',
'1' => 'Yes',
);
?><?php echo form_dropdown('sticky', $options, '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Allow Comments', 'comments'); ?>
<div>
<?php
$options = array(
'' => 'Please Select An Option',
'0' => 'No',
'1' => 'Yes',
);
?><?php echo form_dropdown('comments', $options, '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Date Comments Expire', 'datetime'); ?>
<div>
<input id="datetime" type="datetime" class="required" />
</div>
</div>
<div class="section _100">
<?php echo form_label('Status', 'status'); ?>
<div>
<?php
$options = array(
'' => 'Please Select An Option',
'0' => 'Inactive',
'1' => 'Active',
);
?><?php echo form_dropdown('status', $options, '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Image', 'file'); ?>
<div>
<?php echo form_upload('file', '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Permalink', 'permalink'); ?>
<div>
<?php echo form_input('permalink', '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Article', 'article'); ?><?php $attributes = array('name' => 'article', 'cols' => '30', 'rows' => '5', 'id' => 'article', 'class' => 'required') ?>
<div>
<?php echo form_textarea($attributes); ?>
</div>
</div>
</div><!-- End of .content -->
<div class="actions">
<div class="actions-left">
<?php echo form_reset(array('id' => 'reset', 'name' => 'reset'), 'Reset'); ?>
</div>
<div class="actions-right">
<?php echo form_submit(array('id' => 'submit', 'name' => 'submit'), 'Submit'); ?>
</div>
</div><!-- End of .actions -->
<?php echo form_close(); ?>
EDIT:
I have other forms that use this jquery as well but wondering if anyone had any additional ideas?
I know the answer to this issue... and it drove me nuts so I am happy to help you with this one :))
Codeigniter works in a very special way with POST requests. If you do this but instead use a GET request you will see it works fine... so what's going on?
Codeigniter has a crsf token to make sure you POST your data in a safe way.
So make sure you send this crsf value with the rest of your data.
I will give you an example, this is what my POST ajax + codeigniter looks like:
$.ajax({
type: 'POST',
dataType: 'HTML',
data: {
somevalue : somevalue,
csrf_test_name : $.cookie('csrf_cookie_name')
},
...
As you can see, your crsf value is stored in a cookie. I use the jquery plugin cookie helper, but feel fry to use any other plugin.
However, keep in mind that the name 'csrf_test_name' is always expected by codeigniter when making a POST request
Have a nice day!
For those who want to read more a bout this, this is what I am talking about:
http://aymsystems.com/ajax-csrf-protection-codeigniter-20