Passing variable to the view from zend form using AJAX load - ajax

controller:
public function searchAction()
{
$form = new Application_Form_Search;
$k = $form->getValue('keyword');
$car = new Application_Model_Car();
$mapper = new Application_Model_CarMapper();
$this->view->cars = $mapper->search($keyword);
}
form
<?php
class Application_Form_Search extends Zend_Form {
public function init(){
$this->setMethod('post');
$this->addElement('text', 'keyword', array(
'required' => true,
'label' => 'Keyword:'
));
$this->addElement('button', 'submit', array(
'required' => false,
'ignore' => true,
'label' => 'Search'
));
}
}
?>
original view page
$(document).ready(function(){
$("#submit").click(function(){
$("#main").load('/cars/search');
});
});
Here I am trying to return the search view at the "id=main" section in the original view page by using .load()
In the search view, <?=$this->keyword?> is showing null
it seems like there's problem fetching the keyword field from the form

Ok, you need to set the second variable of .load to send the data. At present you aren't sending the data to the .load function
so it would be more like this. This is assuming that you have id of keyword
$("#main").load('/cars/search', {'keyword':$('input#keyword').val()});
or you could use
$("#main").load('/cars/search', {'keyword':$('[name="keyword"]').val()});
Please see
http://api.jquery.com/load/
Also remember to escape the value so people can't send malicious code through your form.
Hope that helps

Related

Yii2 Kartik editable input value will only change after refresh

I use Kartik Editable input widget. I have a home model and tema model attribute here. Whenever I input and submit value in the field, the value won't change on-the spot but will only change after I refresh the page instead. What should I do? Thanks!
My controller :
public function actionIndex()
{
$searchModel = new HomeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// table only has one row
$model= Home::find()->one();
// Check if there is an Editable ajax request
if (isset($_POST['hasEditable'])) {
// use Yii's response format to encode output as JSON
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
// read your posted model attributes
if ($model->load($_POST)) {
// read or convert your posted information. Based on the 'name' property set in the view. So this 'tema' of $model-> tema comes from 'name' property set in the view.
$value = $model->tema;
$model->save();
// return JSON encoded output in the below format
return ['output'=>$value, 'message'=>'output berhasil'];
// alternatively you can return a validation error
// return ['output'=>'', 'message'=>'Validation error'];
}
// else if nothing to do always return an empty JSON encoded output
else {
return ['output'=>'', 'message'=>'output gagal'];
}
};
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=>$model,
]);
}
The view
<?php
echo Editable::widget([
'model' => $model,
'attribute' => 'tema',
'value'=>$model->tema,
/*'asPopover'=>'false',*/
'type' => 'post',
'header'=>'tema',
'valueIfNull'=>'value-nya NULL',
'format'=>'link',
'size'=> 'lg',
'inputType' => Editable::INPUT_TEXT,
'editableValueOptions' => ['class' => 'text-success h3']
]); ?>
Another issue, whenever I used 'asPopover'=>'false', it shows no error but nothing happen when I click the supposedly editable-input field. The editable-inline field just won't show up. When I use the popOver option,the pop-up just automatically triggered without clicking and also it pop-up on the top left corner of the page. Only after I clicked on the editable widget that triggered the pop-up will it recorrect itself to the proper position. Is it a bug? I used the latest Yii2 with bootstrap 4, and I had set the global parameter in params.php config with 'bsVersion' => '4.x', as in the documentation
In the Controller, try this:
public function actionIndex()
{
$searchModel = new HomeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if (isset($_POST['hasEditable']))
{
$tema = Yii::$app->request->post('editableKey');
$modelHome = Home::findOne($tema);
$posted = current($_POST['Home']);
$post = ['Home' => $posted];
if ($modelHome->load($post)) {
$modelHome->save();
$out = Json::encode(['output'=>$modelHome->tema, 'message'=>'']);
return $out;
}
return;
};
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=>$model,
]);
}

Yii2 Kartik editable widget

I have a problem with my Kartik input text editable widget. It affected on the tema column in my table. The problem is, on my chrome developer tool it returns an "Internal server error" on the AJAX processing. The response header's content is : Content-Type: application/json; charset=UTF-8 but the connection remains close. Is there anything wrong with my code? Note : the initial value of the editable's label is NOT SET (which should be the value of "tema" column retrieved from my $model->tema). The model name is Home.
My HomeController :
public function actionIndex()
{
$searchModel = new HomeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$model = new Home;
// Check if there is an Editable ajax request
if (isset($_POST['hasEditable'])) {
// use Yii's response format to encode output as JSON
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$temaId=Yii::$app->request->post('editableKey');
$query= Home::find()->where(['id'=> $temaId])->one();
// read your posted model attributes
if ($model->load($_POST)) {
// read or convert your posted information
$value = $query->tema;
$value->save();
// return JSON encoded output in the below format
return ['output'=>$value, 'message'=>''];
// alternatively you can return a validation error
// return ['output'=>'', 'message'=>'Validation error'];
} else {
// else if nothing to do always return an empty JSON encoded output
return ['output'=>'', 'message'=>''];
}
};
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=>$model,
]);
}
The view file
use kartik\editable\Editable;
<?php
echo Editable::widget([
'model' => $model,
'attribute' => 'tema',
'type' => 'post',
'value'=>$model->tema,
'header'=>'tema',
'size'=> 'lg',
'inputType' => Editable::INPUT_TEXT,
'editableValueOptions' => ['class' => 'text-success h3']
]);
?>
Please help. Have spent two days on this. Thanks!

Yii2 ActiveForm Ajax Validation and submit

I have made an Active form with validation and ajax submit.
The form is created in view:
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'layout' => 'horizontal',
'method' => 'post',
'enableClientValidation' => false,
'enableAjaxValidation' => true,
'validationUrl' => 'panel/validate',
'fieldConfig' => [
'options' => [
'tag' => false,
],
'template' =>'{input}<p class="help-block help-block-error ">{error}</p>'
],
]); ?>
The validation action:
public function actionValidate()
{
$model = new LoginForm();
$request = \Yii::$app->getRequest();
if ($request->isAjax && $request->isPost && $model->load(Yii::$app->request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
return $this->renderAjax('login', [
'model' => $model,
]);
}
When i leave the fields blank for example, or do not specify the captcha i can see the ajax response:
{"loginform-username":["Username cannot be blank."],"loginform-password":["Password cannot be blank."],"loginform-captcha":["Captcha cannot be blank."]}
However, those errors not getting shown under my form fields. The form fields are created like this:
<?= $form->field($model, 'username')->textInput()
If i turn off ajax validation, the erros are displayed. What can be wrong here?
I'm afraid there is no possible way to display error while turning off 'tag' = false in fieldConfig.
Even though it works for server-side validation, the main problem is how yii.activeForm.js updateInput() function for fields works. When ajax request is completed, the .js tries to find an outer tag (of field) with .field-<model>-<attribute> class selector and fetch error-div children. As long as there is no outer .field tag, no error message is append to form.
I'm not 100% sure about it, but this is my understanding from debugging yii.activeForm.js functionality.
Actually, here is the similar question in yii2/issues, where SilverFire explains that there is no way to achieve this.
ActiveForm fieldConfig options tag=>false will render class attribute without any tag

cakephp passing selection to JS Helper

I want to get the selected schoolFilter form value and place in [SELECTED VALUE HERE].
$data = $this->Js->get('#SchoolFilter')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#SchoolSchoolId')->event(
'change', $this->Js->request(
array('action' => 'assign_school_ads/', [SELECTED VALUE HERE], array(
'update' => '#results',
'data' => $data,
'async' => true,
'dataExpression' => true,
'method' => 'POST'
)
)
);
// School Filter
$schoolFilter = $this->Form->create('School', array('id' => 'SchoolFilter');
$schoolFilter .= $this->Form->input('school_id', array('label'=>'Schools', 'empty'=>'- select -');
$schoolFilter .= $this->Form->end();
I have seen variations on this question but without any clear answer, except to just forget using JS Helper. Is it possible within the context of JS Helper? And if not, can I get the value using regular JQuery, then inject it into JS Helper.
Use following code :-
$this->Js->get('#SchoolFilter');
$this->Js->event('change', $this->Js->request(array('controller'=>'put-ur-controller-ame-here','action' => 'assign_school_ads'),array('async' => true,'update' => '#results','method' => 'post','dataExpression'=>true,'data'=> $this->Js->serializeForm(array('isForm' => true,'inline' => true)))));
the serialize() function sends the form data to the php action so we can see which option was selected and decide what to update in the ajax call.
the form data will be found in $this->data in the action (just like after a form has been submited).
Don't forget to add $this->Js->writeBuffer(); in your layout just before the body closing tag. Otherwise all the ajax code will not be added to your page.

Problem when I am populating data into selectbox through ajax in Drupal

I have installed drupal 6, added some cck fields in one content type. Added two select box fields.
I am taking the selected value of parent select box and as per that selection passing relates options to next select box field using Ajax. (e.g Country -> State. When user selects country I want to pass state values into next select box.)
But when I am submitting the form it gives the following error:
"An illegal choice has been detected. Please contact the site administrator."
I don't know why it is not taking the ajaxified select box values while saving the node.
Does somebody has the solution on it. Is there any solution to handle this dynamic select options in Drupal.
Thanks in advance.
The same thing I'm working on drupal 7 and its work for me. Below is the code. Hope this help you. What I have done is on selection of car model car variant will change and the data save in the table.
function add_offer_form($form, $formstate) {
$form['add_offer_new_car_model'] = array(
'#type' => 'select',
'#required' => TRUE,
'#options' => $car_model,
'#ajax' => array(
'effect' => 'fade',
'progress' => array('type' => 'none'),
'callback' => 'variant_callback',
'wrapper' => 'replace_variant',
),
);
// Combo box to select new car variant
$form['add_offer_new_car_variant'] = array(
'#type' => 'select',
'#options' => array(),
// The prefix/suffix provide the div that we're replacing, named by #ajax['wrapper'] above.
'#prefix' => '<div id="replace_variant">',
'#suffix' => '</div>',
);
// An AJAX request calls the form builder function for every change.
// We can change how we build the form based on $form_state.
if (!empty($formstate['values']['add_offer_new_car_model'])) {
$model_id = $formstate['values']['add_offer_new_car_model'];
$rows = array();
$result = db_query("SELECT id, variant_name from {va_car_variant} where car_model_id in ($model_id,1) order by variant_name");
while ($data = $result->fetchObject()) {
$id = $data->id;
$rows[$id] = $data->variant_name;
}
$form['add_offer_new_car_variant']['#options'] = $rows;
}
}
////////////////////////////////////////////////////////
///////// FUNCTION FOR AJAX CALL BACK
function variant_callback($form, &$form_state) {
return $form['add_offer_new_car_variant'];
}

Resources