X
X
XenK2016-10-22 07:43:41
JavaScript
XenK, 2016-10-22 07:43:41

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(); ?>

controller:
public function actionImage() {
    $json = ['response' => 'ok'];
    \Yii::$app->response->format = Response::FORMAT_JSON;
    return $json;
}

JS:
$('.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();
    });
}

In fact, when you click on the image, nothing happens. Is this approach correct? If yes, what is the error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2016-10-22
@webinar

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 question

Ask a Question

731 491 924 answers to any question