doukanhua0752
doukanhua0752
2017-02-16 21:23

无法从POST请求中获取数据

已采纳

I want to get data from POST request. I have form which create this POST request and redirect it to some action, you can see that in this line:

<?php $form = ActiveForm::begin([
        'id' => 'my-form',
        'options' => ['enctype' => 'multipart/form-data'],
        'action' => ['site/form']
    ]); ?>

then some method,in my case actionForm() in SiteController must to handle this request. I need to get that data and save it to db. I have model for that:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "form".
 *
 * @property integer $id
 * @property string $name
 * @property string $email
 * @property integer $age
 * @property integer $height
 * @property integer $weight
 * @property string $city
 * @property string $techies
 * @property string $english_level
 * @property resource $photo_1
 * @property resource $photo_2
 * @property resource $photo_3
 * @property resource $photo_4
 * @property resource $photo_5
 */
class Form extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'form';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'email', 'age', 'height', 'weight', 'city', 'techies', 'english_level', 'photo_1', 'photo_2', 'photo_3', 'photo_4', 'photo_5'], 'required'],
            [['name', 'email', 'city', 'techies', 'english_level', 'photo_1', 'photo_2', 'photo_3', 'photo_4', 'photo_5'], 'string'],
            [['age', 'height', 'weight'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'email' => 'Email',
            'age' => 'Age',
            'height' => 'Height',
            'weight' => 'Weight',
            'city' => 'City',
            'techies' => 'Techies',
            'english_level' => 'English Level',
            'photo_1' => 'Photo 1',
            'photo_2' => 'Photo 2',
            'photo_3' => 'Photo 3',
            'photo_4' => 'Photo 4',
            'photo_5' => 'Photo 5',
        ];
    }
}

this is model that created from gii model generator. I also have table in my db named form and with all rows. In my db.php I have all configuration for db. But when I clicked button in my form,page only reload without anything creating. Action in controller:

public function actionForm()
{
    $Form = new Form();
    if (($loaded = $Form->load(Yii::$app->request->post('form'))) && $Form->save()) {
                return 'ok';
    }elseif($loaded){
 var_dump($Form->getErrors());
 }

    return $this->render('form',array(
       'Form' => $Form,
    ));
}
when all good that method must to show "ok" or errors,but nothing happened,but something must to happen.

My view file:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use dosamigos\fileupload\FileUploadUI;
?>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<?php $form = ActiveForm::begin([
        'id' => 'my-form',
        'options' => ['enctype' => 'multipart/form-data'],
        'action' => ['site/form']
    ]); ?>
    <div class="row">
        <div class="col-lg-6">
            <?= $form->field($Form, 'name')->textInput(['class'=>'name_class'])->input('name',['placeholder' => "Имя"])->label(false); ?>
        </div>
        <div class="col-lg-6">
            <?= $form->field($Form, 'email')->textInput()->input('email',['placeholder' => "E-mail"])->label(false); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <?= $form->field($Form, 'age')->textInput()->input('age',['placeholder' => "Возраст(полных лет)"])->label(false); ?>
        </div>
        <div class="col-lg-6">
            <?= $form->field($Form, 'height')->textInput()->input('height',['placeholder' => "Рост"])->label(false); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <?= $form->field($Form, 'weight')->textInput()->input('weight',['placeholder' => "Вес"])->label(false); ?>
        </div>
        <div class="col-lg-6">
            <?= $form->field($Form, 'city')->textInput()->input('city',['placeholder' => "Город проживания"])->label(false); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-3">
            <p><img class="describe_images" src="computer.png"></img>Нужна ли техника в аренду</p>
        </div>
        <?= $form->field($Form, 'techies')->checkboxList(['no'=>'Нет', 'yes_camera'=>'Да,только камера', 'yes_both'=>'да,компьютер и камера'])->label(false) ?>
    </div>
    <div class="row">
        <div class="col-lg-3">
            <p><img class="describe_images" src="English.png"></img>Знание английского</p>
        </div>

        <?= $form->field($Form, 'english_level')->checkboxList(['starter'=>'Без знания', 'elementary'=>'Базовый', 'intermediate'=>'Средний','up-intermediate'=>'Высокий','advanced'=>'Превосходный'])->label(false) ?>
    </div>
        <script>
        $('#my-form').submit( function(e) {
        e.preventDefault();

        var data = new FormData(this); // <-- 'this' is your form element

        $.ajax({
                url: 'index.php/Form',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data){
                    alert(data);
                },
                error: function(){
            alert('ERROR at PHP side!!');
        }
    });
    });

        </script>
        <script>
        $(function() {
        // Multiple images preview in browser
        var imagesPreview = function(input, placetoinsert) {

            if (input.files) {
                var filesAmount = input.files.length;

                for (i = 0; i < filesAmount; i++) {
                    var reader = new FileReader();

                    reader.onload = function(event) {
                        $($.parseHTML('<img>')).attr('src', event.target.result).appendTo('.preview');
                    }

                    reader.readAsDataURL(input.files[i]);
                }
            }

        };

        $('#gallery-photo-add').on('change', function() {
            imagesPreview(this, 'div.gallery');
        });
    });
    </script>
    <div class="row">
        <div class="col-lg-6">
<div class="col-lg-6">
            <p class="add_photo"><img class="describe_images" src="photo.png"></img>Добавить фото(до 5 штук)</p>

   </div>
   <div class="col-lg-6">
 <?= $form->field($Form, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
   </div>


        </div>

        <div class="col-lg-6 pixels-line">
            <div class="preview"></div>
        </div>
    </div>
    <div class="form-group">
        <?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
    </div>
<?php ActiveForm::end() ?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • drtwqc3744 drtwqc3744 4年前

    If you are using PHP version >5.4, use as per below changes

    Yii:$app->request->post('form')['name']; //For PHP > 5.4
    //or for PHP < 5.4 :
    $post =Yii::$app->request->post('UserFormModel');
    
    点赞 评论 复制链接分享
  • douchao0358 douchao0358 4年前

    In the form action you have 'action' => ['site/form'] which creates Url relative to the current controller i.e. 'site/site/form' instead of that use 'action' => ['/site/form'] this will solve your problem or you can only provide the controller's action which handles the form if your form is served by the same controller.

    点赞 评论 复制链接分享

为你推荐