Answer the question
In order to leave comments, you need to log in
How to implement different behavior on different Submits in PJAX wrapped form?
There is a one field form wrapped with pjax and two submit buttons - Add and Replace.
I tried to specify name / value, formaction for buttons - the desired effect was not achieved - the form action is executed, name / value, formaction do not affect the data transmitted to the controller.
It is necessary to pass different values of myParam, depending on the button.
The user input elements are omitted in the code example.
Pjax::begin([
'enablePushState' => false,
'timeout'=> 5000,
'id'=> 'pjax1',
'submitEvent' => 'submit',
'formSelector' => '#'.'form1'
]);
$form = ActiveForm::begin([
'id' => 'form1',
'action' => Url::to(['my-controller/work1']),
'options' => [
'data-pjax' => 'pjax1'
]
]);
$ParamsInput = [];
$ParamsInput['class'] = 'btn btn-success';
$ParamsInput['formaction'] = Url::to(['my-controller/work1', 'myParam' => false]);
echo Html::submitButton('Добавить', $ParamsInput);
echo Html::hiddenInput('myParam', false);
$ParamsInput['name'] = 'myParam';
$ParamsInput['value'] = 'true';
$ParamsInput['formaction'] = Url::to(['my-controller/work1', 'myParam' => true]);
echo Html::submitButton('Заменить', $tmpParamsInput);
ActiveForm::end();
Pjax::end();
Answer the question
In order to leave comments, you need to log in
Controller
public function actionIndex()
{
if(Yii::$app->request->isAjax){
if(Yii::$app->request->post('myParam') == 1){
$param = 'Ответ сервера - ' . Yii::$app->request->post('myParam');
}
else{
$param = 'Ответ сервера - ' . Yii::$app->request->post('myParam');
}
return $this->asJson($param);
}
return $this->render('index');
}
<?php
$form = ActiveForm::begin([
'id' => 'form1',
'action' => Url::to(['images/index']),
'options' => [
'data-pjax' => 'pjax1'
]
]);
echo Html::submitButton('Добавить', ['data' => ['param' => 1]]);
echo Html::hiddenInput('myParam', false);
echo Html::submitButton('Заменить', ['data' => ['param' => 0]]);
ActiveForm::end();
?>
<div id="result"></div>
<?php
$this->registerJs("
$('button').on('click', function(e){
e.preventDefault();
var url = $(this).closest('form').attr('action');
var param = $(this).attr('data-param')
$.ajax({
url: url,
type: 'POST',
data: {myParam: param},
success: function(data){
$('#result').text(data)
}
})
})
")
?>
An html form cannot have 2 different actions.
You can make the same name and different value for 2 submitButton
<input type="submit" name="action" value="Update" />
<input type="submit" name="action" value="Delete" />
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question