doukanhua0752 2017-02-16 21:23
浏览 671
已采纳

无法从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 2017-02-17 04:30
    关注

    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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)