Answer the question
In order to leave comments, you need to log in
How to correctly submit a YII2 form, with hidden fields?
Suppose there are 3 pictures, by clicking on any of them, I need to identify the one on which the click was made, and accordingly send data about it to the server.
The first thing that came to mind was to do this:
Add an ID to the pictures, and after clicking, change the value of the Input, and then send it:
View:
<img src="/img1.png" id="img1" class="imageSelect">
<img src="/img2.png" id="img2" class="imageSelect">
<img src="/img3.png" id="img3" class="imageSelect">
<?php ActiveForm::begin(['id' => 'form1', 'action' => '/image']); ?>
<?= Html::hiddenInput('ImageNum', ''); ?>
<?php ActiveForm::end(); ?>
public function actionImage() {
$json = ['response' => 'ok'];
\Yii::$app->response->format = Response::FORMAT_JSON;
return $json;
}
$('.imageSelect').click(function () {
$('input[name=ImageNum]').val($(this).attr('id'));
Send();
});
function Send() {
$('#form1').submit(function (e) {
var url = '/image';
$.ajax({
type: "POST",
url: url,
data: $('form1').serialize(),
success: function (data) {
console.log(data);
}
});
e.preventDefault();
});
}
Answer the question
In order to leave comments, you need to log in
Is it necessary to submit the entire form by clicking on the image? Maybe just do ajax on click and send the id of the image? According to your action, it is not clear why he is. It does nothing but return 'response' => 'ok'.
You can even wrap each image in a link:
echo Html::a('<img src="/img1.png" id="img1" class="imageSelect">', ['/mycontroller/image', 'id' => $model->id], [
'data' => [
'confirm' => 'Вы точно хотите выбрать это фото?',
'method' => 'post',
],
]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question