Вот нашел пример помогите понять на пальцах азы.
это контроллер
Код: Выделить всё
public function actionSubmit(){
if( isset( $_GET['textdata'] ) ){
$data = '';
foreach($_GET as $key => $item){
if( mb_stripos($key, 'title') > 0 || mb_stripos($key, 'text') > 0 ){
$data = $key;
}
}
$dataModel = json_decode($data);
$model = new Posts;
$model->title = $dataModel->title;
$model->text = $dataModel->text;
$model->author_id = Yii::$app->user->id;
$model->hits = 0;
$model->data = date("Y-m-d");
$model->save();
echo $data;
}
if( Yii::$app->request->isAjax ){
}
}
public function actionSubmitfile(){
$model = Posts::find()->where([ 'author_id' => Yii::$app->user->id ])->orderBy([ '`id`' => SORT_DESC ])->one();
$data = array();
if( isset( $_GET['uploadfiles'] ) ){
$error = false;
$files = array();
//$uploaddir = './uploads/'; // . - текущая папка где находится submit.php
$uploaddir = './img/posts/'; // . - текущая папка где находится submit.php
// Создадим папку если её нет
if( ! is_dir( $uploaddir ) ) mkdir( $uploaddir, 0777 );
// переместим файлы из временной директории в указанную
foreach( $_FILES as $file ){
if( move_uploaded_file( $file['tmp_name'], $uploaddir . basename($file['name']) ) ){
$files[] = realpath( $uploaddir . $file['name'] );
}
else{
$error = true;
}
}
$model->intro_image = $file['name'];
$model->save();
$data = $error ? array('error' => 'Ошибка загрузки файлов.') : array('files' => $files );
echo json_encode( $data );
}}
это вью
Код: Выделить всё
<?php
use yii\helpers\Url;
use frontend\models\Likes;
use frontend\models\Comments;
use frontend\models\Posts;
use frontend\models\Subscribe;
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use yii\widgets\LinkPager;
use yii\widgets\Pjax;
$script3 = <<< JS
var files;
$('input[type=file]').change(function(){
files = this.files;
console.log(files);
});
$('form#profile-newpost').on('beforeSubmit', function(e){
console.log('beforeSubmit');
var data = new FormData();
$.each( files, function( key, value ){
data.append( key, value );
});
var title = $('.post-block .input-title').val();
var text = $('.rightside .post-block textarea').val();
var textData = {
title: title,
text: text,
};
textData = JSON.stringify(textData);
$.ajax({
url: "submit?textdata",
type: "GET",
data: textData,
cache: false,
contentType: "application/json; charset=utf-8", // Так jQuery скажет серверу что это строковой запрос
success: function( data, textStatus, jqXHR ){
if( typeof data.error === "undefined" ){
data = JSON.parse(data);
console.log(files);
console.log(data);
if( files ){
var uploadFile = "../uploads/" + files[0].name;
}
jQuery('.profile .rightside').prepend('<div class="post-profile"><div class="left"><img class="main-picture" src=' + uploadFile + ' alt=""></div><div class="right"><span></span><br><h3>' + data.text + '</h3><h5></h5></div></div>');
$('.post-block .input-title').val('');
$('.rightside .post-block textarea').val('');
jQuery('.add-post').show();
jQuery('.post-block').addClass('dNone');
jQuery('.profile .rightside').prepend(jQuery('.add-post'));
}
else{
console.log('ОШИБКИ ОТВЕТА сервера: ' + data.error );
}
},
error: function( jqXHR, textStatus, errorThrown ){
console.log('ОШИБКИ AJAX запроса2: ' + textStatus );
}
});
$.ajax({
url: "submitfile?uploadfiles",
type: "POST",
data: data,
cache: false,
dataType: "json",
processData: false,
contentType: false,
success: function( respond, textStatus, jqXHR ){
if( typeof respond.error === "undefined" ){
var files_path = respond.files;
var html = "";
$.each( files_path, function( key, val ){ html += val +"<br>"; } )
//$(".ajax-respond").html( html );
}
else{
console.log("ОШИБКИ ОТВЕТА сервера: " + respond.error );
}
},
error: function( jqXHR, textStatus, errorThrown ){
console.log("ОШИБКИ AJAX запроса: " + textStatus );
}
});
return false;
});
JS;
$this->registerJs($script3);?>
<? Pjax::begin();?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'], 'id' => 'profile-newpost']); ?>
<?=Html::input('text', 'title', '', ['class' => 'input-title', 'placeholder' => 'enter title'])?>
<?=Html::textarea('text', '', ['class' => 'add-post-text', 'placeholder' => 'write your post'])?>
<?=Html::input('file', 'file')?>
<div class="buttons">
<?= Html::submitButton('publish', [ 'class' => 'btn btn-success save-post', 'id' => 'clickButton' ]) ?>
<?= Html::submitButton('cancel', [ 'class' => 'btn btn-danger cancel-post' ]) ?>
</div>
<?php ActiveForm::end(); ?>
<div id="message"></div>
<? Pjax::end();?>