Yii2 save image to database as base64 - php

I am trying to save image as a base64 into database. But when I submit form I am getting the image NULL. I couldn't understand what's wrong.
VIEW:
<div class="content">
<?php $form = ActiveForm::begin([
'id' => 'products-add-form',
'action' => ['products/product-add-form'],
'method' => 'post',
'options' => [
'class' => 'products-tbl-style',
'enctype' => 'multipart/form-data',
]
]); ?>
<?= $form->field($model, 'productName'); ?>
<?= $form->field($model, 'cost'); ?>
<?= $form->field($model, 'available')->dropDownList(['Y' => 'Yes', 'N' => 'No']); ?>
<?= $form->field($model, 'image')->fileInput(['class'=>'btn btn-primary']); ?>
<?= Html::submitButton('Save', ['class'=>'btn btn-success products-save-btn']); ?>
<?php ActiveForm::end(); ?>
</div>
Controller:
if($model->load(Yii::$app->request->post())){
$file = UploadedFile::getInstance($model,'image');
var_dump($file->name);
var_dump($file);
var_dump($_FILES);
}
Model:
public function rules()
{
return [
[['productName', 'cost', 'available', 'image'], 'required'],
[['cost'], 'number'],
[['available'], 'string', 'max' => 1],
[['image'], 'string'],
[['productName'], 'string', 'max' => 100]
];
}
Here my JQuery code, I am submitting the form data via ajax, does it cause a problem?
JS:
$("form#products-add-form").on('beforeSubmit', function(e){
var form = $(this);
$.post(
form.attr('action'),
form.serialize()
)
.done(function(result){
if(result == 1){
form.trigger("reset");
$.pjax.reload({container:'#products-table'});
$.notify({
icon: "pe-7s-check",
message: "New product is added"
},{
type: type[2],
timer: 10,
placement: {
from: 'top',
align: 'right'
}
});
}
else {
alert(result);
}
}).fail(function(){
console.log("server error");
});
return false;
});

To send files via AJAX you shoud use FormData. To construct a FormData object that contains the data from an existing <form>, specify that form element when creating the FormData object:
$("form#products-add-form").on('beforeSubmit', function(e){
$.post(
form.attr('action'),
new FormData(this) /* this is a form object */
)
/* your other code here */
});
UPD: As TS mentioned it should be processData set to false. It's impossible to set it for $.post, so we need to use $.ajax

I have tried following :
$.ajax( {
url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
And now it's working, as #SiZE wrote, we need to send file input with FormData() via ajax.

You can try to use FileInput widget it work's perfectly.

Related

Yii2- Unable to upload image

I am working on yii2. In one of my view, I am trying to upload an image. But I am unable to upload it.
Model
class MeterAcceptanceHeader extends \yii\db\ActiveRecord
{
public static $status_titles =[
0 => 'Prepared',
1 => 'Created',
2 => 'Printed',
3 => 'Canceled',
];
/**
* #inheritdoc
*/
public static function tableName()
{
return 'meter_acceptance_header';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['sub_div', 'prepared_by'], 'required'],
[['prepared_by', 'updated_by'], 'integer'],
[['prepared_at', 'updated_at'], 'safe'],
[['sub_div', 'meter_type', 'status'], 'string', 'max' => 100],
[['images'], 'string', 'max' => 255],
[['images'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png,jpg,pdf', 'maxFiles' => 4],
[['sub_div'], 'exist', 'skipOnError' => true, 'targetClass' => SurveyHescoSubdivision::className(), 'targetAttribute' => ['sub_div' => 'sub_div_code']],
[['prepared_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['prepared_by' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'sub_div' => 'Sub Div',
'meter_type' => 'Meter Type',
'prepared_by' => 'Prepared By',
'prepared_at' => 'Prepared At',
'updated_at' => 'Updated At',
'status' => 'Status',
'updated_by' => 'Updated By',
'images' => 'Document Snap',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getMeterAcceptanceDetails()
{
return $this->hasMany(MeterAcceptanceDetails::className(), ['accpt_id' => 'id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSubDiv()
{
return $this->hasOne(SurveyHescoSubdivision::className(), ['sub_div_code' => 'sub_div']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPrepared()
{
return $this->hasOne(User::className(), ['id' => 'prepared_by']);
}
}
MeterAcceptanceHeader Table
MeterAcceptanceImages Table
There is a form1 in which user is prompt to select from the dropdown.
Form1 View
<div class="meter-acceptance-header-form">
<?php $model->status = common\models\MeterAcceptanceHeader::$status_titles[0]; ?>
<?php $form = ActiveForm::begin(['id'=>'acceptance-form','options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'sub_div')->dropDownList([''=>'Please Select'] + \common\models\SurveyHescoSubdivision::toArrayList()) ?>
<?= $form->field($model, 'meter_type')->dropDownList([''=>'Please Select','Single-Phase' => 'Single-Phase', '3-Phase' => '3-Phase', 'L.T.TOU' => 'L.T.TOU']) ?>
<?= $form->field($model, 'status')->textInput(['maxlength' => true,'readonly' => true]) ?>
<div class="form-group">
<a class="btn btn-default" onclick="window.history.back()" href="javascript:;"><i
class="fa fa-close"></i>
Cancel</a>
<a class="<?= $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary' ?>" onclick="
$('#acceptance-form').submit();" href="javascript:">
<?= $model->isNewRecord ? 'Create' : 'Update' ?></a>
</div>
<?php ActiveForm::end(); ?>
After clicking on Create button the user is prompt to the second form in which a user will upload an image.
Below is my code for the controller from which I am trying to upload it.
public function actionSetpdf($id)
{
$model = $this->findModel($id);
$m = 0;
$accpt_id = $model->id;
$meter_type = $model->meter_type;
$ogp_sub_div = $model->sub_div;
$images=[];
$ic=0;
$files_uploaded = false;
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
foreach($data as $value)
{
$m = new MeterAcceptanceDetails;
$m -> load(Yii::$app->request->post());
$m->accpt_id = $accpt_id;
$m->meter_type = $meter_type;
$m->created_at = date('Y-m-d H:i:s');
$m->created_by = Yii::$app->user->id;
$m->meter_id = $value;
$m->meter_msn = \common\models\Meters::idTomsn($value);
$m->flag = 1;// 1 means created
$m->ogp_sub_div = $ogp_sub_div;
if($m->save())
{
// Here the upload image code starts
if($ic==0)
{
$model->images = UploadedFile::getInstances($model, 'images');
foreach ($model->images as $file)
{
if (file_exists($file->tempName))
{
$img_s = new MeterAcceptanceImages;
$file_name = rand(0, 1000) . time().date('his') . '.' . $file->extension;
$file->saveAs('uploads/meter_acceptance/' . $file_name);
$img_s->file_path = $file_name;
$img_s->accpt_id = $accpt_id;
if ($img_s->save()) {
$images[] = $img_s;
} else {
print_r($img_s->getErrors());
}
}
}
}else{
foreach($images as $image){
$img_s = new MeterAcceptanceImages;
$img_s->file_path = $image->file_path;
$img_s->accpt_id = $accpt_id;
$img_s->save();
}
}
$model->status = MeterAcceptanceHeader::$status_titles[1];
$model->update();
}
else{
$this->renderAjax('viewcreated');
}
}
}
else{
$this->renderAjax('viewcreated');
}
return $this->redirect(Url::toRoute(['meteracceptanceheader/viewsetpdf','id' => $model->id,'model' => $this->findModel($id)]));
}
Form2 View
<div class="map-meters-form" id="doc">
<?php $form = ActiveForm::begin(['id' => 'map-form', 'enableClientValidation' => true, 'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data']]) ?>
<section class="content">
<div class="box">
<div id="chk" class="box-body">
<?php Pjax::begin(); ?>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'label'=>'Serial #',
'value' => function($d)
{
return $d->id;
}
],
[
'label' => 'Meter Type',
'value' => function ($d) {
if(is_object($d))
return $d->meter_type;
return ' - ';
},
],
'sub_div',
[
'label' => 'Sub Division Name',
'value' => function ($d) {
if(is_object($d))
return $d->subDiv->name;
return '-';
},
],
[
'label' => 'Prepared By',
'value' => function ($d) {
if(is_object($d))
return $d->prepared->name;
},
],
'prepared_at',
'status',
],
]) ?>
<br>
<div class="pre-scrollable">
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'ajaxUpdate' => true,
'filterModel' => false,
//'id'=>'gv',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Meter_Type',
'Sub_Division_Code',
'Sub_Division_Name',
],
]); ?>
</div>
<?php Pjax::end(); ?>
<?= $form->field($model, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*'])?>
<br>
<form>
<p>
Submit
<br/>
</p>
</form>
</div>
</div>
</section>
<?php ActiveForm::end(); ?>
</div>
<?php
$url = Url::toRoute(['/meteracceptanceheader/setpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {
$(document).on('pjax:end', function() {
$("#chk").find("input:checkbox").prop("checked", true);
});
$("#chk").find("input:checkbox").prop("checked", true);
$('#myid').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: '$url',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
})
});
JS;
$this->registerJs($script, \yii\web\View::POS_END);
?>
This will allow selecting an image. Now when I try to click submit button I am getting below error
PHP Notice 'yii\base\ErrorException' with message 'Undefined offset: 0'
in
E:\xampp\htdocs\inventory-web\vendor\yiisoft\yii2\db\Command.php:330
By debugging the controller code I found that the error comes at foreach ($model->images as $file) as print_r($model->images) return Array() empty.
By doing print_r($model) I got
common\models\MeterAcceptanceHeader Object ( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 1 [sub_div] => 37111 [meter_type] => L.T.TOU [prepared_by] => 12 [prepared_at] => 2018-08-20 12:41:27 [updated_at] => [status] => Prepared [updated_by] => [images] => Array ( ) ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 1 [sub_div] => 37111 [meter_type] => L.T.TOU [prepared_by] => 12 [prepared_at] => 2018-08-20 12:41:27 [updated_at] => [status] => Prepared [updated_by] => [images] => ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ) )
I have used the same process in other modules as well and it works properly.
How can I get rid of this problem?
Update 1
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use app\models\User;
use yii\widgets\DetailView;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;
use kartik\select2\Select2;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = $model->id;
$this->title = 'Meter Acceptance Form';
$this->params['breadcrumbs'][] = $this->title;
?>
<section class="content-header">
<h1>Meter Acceptance</h1>
</section>
<div class="map-meters-form" id="doc">
<section class="content">
<div class="box">
<div id="chk" class="box-body">
<?php Pjax::begin(); ?>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
[
'label' => 'Serial #',
'value' => function($d){
return $d->id;
}
],
[
'label' => 'Meter Type',
'value' => function ($d){
if( is_object($d) )
return $d->meter_type;
return ' - ';
},
],
'sub_div',
[
'label' => 'Sub Division Name',
'value' => function ($d){
if( is_object($d) )
return $d->subDiv->name;
return '-';
},
],
[
'label' => 'Prepared By',
'value' => function ($d){
if( is_object($d) )
return $d->prepared->name;
},
],
'prepared_at',
'status',
],
])
?>
<br>
<div class="pre-scrollable">
<?=
GridView::widget([
'dataProvider' => $dataProvider,
//'ajaxUpdate' => true,
'filterModel' => false,
//'id'=>'gv',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d){
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Meter_Type',
'Sub_Division_Code',
'Sub_Division_Name',
],
]);
?>
</div>
<?php Pjax::end(); ?>
<?php
$form = ActiveForm::begin(['id' => 'map-form', 'enableClientValidation' => true, 'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data']])
?>
<?=$form->field($model, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<br>
<p>
Submit
<br/>
</p>
<?php ActiveForm::end(); ?>
</div>
</div>
</section>
</div>
<?php
$url = Url::toRoute(['/meteracceptanceheader/setpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {
$(document).on('pjax:end', function() {
$("#chk").find("input:checkbox").prop("checked", true);
});
$("#chk").find("input:checkbox").prop("checked", true);
$('#myid').on('click',function(e) {
e.preventDefault();
//START Append form data
var data = new FormData();
var files= $('input[name="MeterAcceptanceHeader[images][]"]')[0].files;
//append files
$.each(files,function(index,file){
data.append("MeterAcceptanceHeader[images][]",file,file.name);
});
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
//alert(strValue);
//append your query string to the form data too
data.append('data',strValue);
//END append form data
$.ajax({
url: '$url',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: {data:strValue},
success: function(data) {
alert(data);
}
});
})
});
JS;
$this->registerJs($script, \yii\web\View::POS_END);
?>
Any help would be highly appreciated.
What looks like that you are trying to submit an image via Ajax call when you click on submit button in the step 2 for image upload as you are binding the click to the #myid which is the anchor button
Submit
And if you are trying to send the image via ajax you need to use the FormData interface.
The FormData interface provides a way to easily construct a set of
key/value pairs representing form fields and their values, which can
then be easily sent using the XMLHttpRequest.send() method. It uses
the same format a form would use if the encoding type were set to
"multipart/form-data".
But before I address how to do it, you need to look into some other issues related to Form2 view.
You are nesting the 2 forms which is technically wrong and you can't do that see Why.
Above all why are you creating a separate form for the submit button?
see this line on top
<?php $form = ActiveForm::begin(['id' => 'map-form', 'enableClientValidation' => true, 'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data']]) ?>
This is where your first form starts and the file input field
<?= $form->field($model, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*'])?>
is inside this form, and on the very next line you have the anchor button that i mentioned above in the start but you are wrapping it inside a separate form and that too before you close the ActiveForm
<form>
<p>
Submit
<br/>
</p>
</form>
instead you are closing the ActiveForm after this form by calling <?php ActiveForm::end(); ?>. As you have seen in the previous question that you faced weird behavior with the filter inputs for the GridVew as you were wrapping the GridView inside the form, and you are repeating that same mistake here too and also nesting 2 forms within.
What i will advise you to do first
Remove the form that you are creating just for the anchor button, as you wont be needing it if you want to submit the image via ajax by clicking on the anchor just keep the anchor inside the main ActiveForm. And Move the ActiveForm::begin() just before the fileInput() and after the Pjax::end().
With that said you should now user FormData to upload the image via ajax and to do so you have to add these options contentType: false and processData: false inside your ajax call and use FormData.append() to append the input files to the FormData.
So your javascript for the click function will look like this, i assume the model used for the image upload is MeterAcceptanceImages
$('#myid').on('click',function(e) {
event.preventDefault();
//START Append form data
let data = new FormData();
let files= $("input[name='MeterAcceptanceImages[images][]']")[0].files;
//append files
$.each(files,function(index,file){
data.append('MeterAcceptanceImages[images][]',file,file.name);
});
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!==""){
strValue = strValue + " , " + this.value;
}else{
strValue = this.value;
}
});
//append your query string to the form data too
data.append('data',strValue);
//END append form data
$.ajax({
url: '$url',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: data,
success: function(data) {
alert(data);
}
});
});
So overall your view Form2.php should look like below
<div class="map-meters-form" id="doc">
<section class="content">
<div class="box">
<div id="chk" class="box-body">
<?php Pjax::begin(); ?>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
[
'label' => 'Serial #',
'value' => function($d){
return $d->id;
}
],
[
'label' => 'Meter Type',
'value' => function ($d){
if( is_object($d) )
return $d->meter_type;
return ' - ';
},
],
'sub_div',
[
'label' => 'Sub Division Name',
'value' => function ($d){
if( is_object($d) )
return $d->subDiv->name;
return '-';
},
],
[
'label' => 'Prepared By',
'value' => function ($d){
if( is_object($d) )
return $d->prepared->name;
},
],
'prepared_at',
'status',
],
])
?>
<br>
<div class="pre-scrollable">
<?=
GridView::widget([
'dataProvider' => $dataProvider,
//'ajaxUpdate' => true,
'filterModel' => false,
//'id'=>'gv',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d){
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Meter_Type',
'Sub_Division_Code',
'Sub_Division_Name',
],
]);
?>
</div>
<?php Pjax::end(); ?>
<?php
$form = ActiveForm::begin(['id' => 'map-form', 'enableClientValidation' => true, 'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data']])
?>
<?=$form->field($model, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<br>
<p>
Submit
<br/>
</p>
<?php ActiveForm::end(); ?>
</div>
</div>
</section>
</div>
<?php
$url = Url::toRoute(['/meteracceptanceheader/setpdf', 'id' => $model->id]);
$script = <<< JS
$(document).ready(function () {
$(document).on('pjax:end', function() {
$("#chk").find("input:checkbox").prop("checked", true);
});
$("#chk").find("input:checkbox").prop("checked", true);
$('#myid').on('click',function(e) {
event.preventDefault();
//START Append form data
let data = new FormData();
let files= $("input[name='MeterAcceptanceImages[images][]']")[0].files;
//append files
$.each(files,function(index,file){
data.append('MeterAcceptanceImages[images][]',file,file.name);
});
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!==""){
strValue = strValue + " , " + this.value;
}else{
strValue = this.value;
}
});
//append your query string to the form data too
data.append('data',strValue);
//END append form data
$.ajax({
url: '$url',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: data,
success: function(data) {
alert(data);
}
});
});
});
JS;
$this->registerJs($script, \yii\web\View::POS_END);
?>
Now if you try to print_r(UploadedFile::getInstances('images')) should show you all the images you selected and submitted to upload. To troubleshoot in case of errors while uploading of the ajax call you can see my answer i posted previously related to ajax file uploads.

yii2 - How to get checked checkbox values from gridview to controller

I need to get checked checkbox value from my view to controller when button is press.
Gridview :
<div class="installment-ready">
<!-- <h1><?= Html::encode($this->title) ?></h1> -->
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
[
'class' => 'yii\grid\SerialColumn',
'contentOptions'=>[ 'style'=>'width: 60px'],
],
//Checkbox
[
'class' => 'yii\grid\CheckboxColumn',
'contentOptions'=>[ 'style'=>'width: 50px'],
'name' => 'checked',
'checkboxOptions'=> function($model, $key, $index, $column) {
return ["value" => $model->ACCOUNT_ID];
}
],
Button to process selected checkbox:
<?= Html::a('Submit', ['#'], ['class' => 'btn btn-success pull-right']) ?>
In your controller action use below code
Yii::$app->request->post('checked');
I found a solution. I'm using ajax to post selected checkbox to my controller.
Script that I use in my view
<script type="text/javascript">
// action for all selected rows
function submit(){
var dialog = confirm("Are you sure to submit the installment?");
if (dialog == true) {
var keys = $('#grid').yiiGridView('getSelectedRows');
// console.log(keys);
var ajax = new XMLHttpRequest();
$.ajax({
type: "POST",
url: 'index.php?r=installment/submit', // Your controller action
data: {keylist: keys},
success: function(result){
console.log(result);
}
});
}
}
</script>
<!-- Submit button -->
<button type="button" onclick="submit()" class="btn btn-success pull-right">Submit</button
And you can use usual Yii::$app->request->post() in controller to get your data.

Cakephp form pass upload file to controller via ajax

I have a form which is created using cakephp form builder, this form has a couple of file upload fields as below:
<?php echo $this->Form->create('application', array('type' => 'file', 'url' => array('app' => true, 'controller' => 'jobs', 'action' => 'save_new_application'), 'id' => 'create-application-form'));
echo '<p>'.$this->Form->input('cv', array('type' => 'file', 'label' => "Upload CV (Required)", 'required' => true)).'</p>';
echo '<p>'.$this->Form->input('cover-letter', array('type' => 'file', 'label' => "Upload Cover Letter (optional)")).'</p>';
echo $this->Form->input('campaignid', array('type' => 'hidden', 'class' => 'form-control sendid', 'label' => false, 'value' => $campaignid));
echo $this->Form->input('profileid', array('type' => 'hidden', 'class' => 'form-control sendid', 'label' => false, 'value' => $profileid));
echo $this->Form->submit('Apply', array('class' => 'form-control')); ?>
<?php echo $this->Form->end(); ?>
I however need this form to be submitted via ajax so that the page doesnt refresh, as with other forms on the site I have the below jquery, however the controller only gets the two hidden fields and no information about the upload files.
$('#create-application-form').off().on('submit', function(e){
e.preventDefault();
$.ajax({
url: '/app/jobs/save_new_application/',
dataType: 'json',
method: 'post',
data: $(this).serialize()
})
.done(function(response) {
//show result
if (response.status == 'OK') {
} else if (response.status == 'FAIL') {
} else {
//show default message
}
})
.fail(function(jqXHR) {
if (jqXHR.status == 403) {
window.location = '/';
} else {
console.log(jqXHR);
}
});
});
What do i need to change in the ajax call to be able to pass the actual file data to the controller so the files can be saved on the server?
You have to send New FormData() object to send file using ajax
Updated code
$('#create-application-form').off().on('submit', function(e){
e.preventDefault();
var formdatas = new FormData($('#create-application-form')[0]);
$.ajax({
url: '/app/jobs/save_new_application/',
dataType: 'json',
method: 'post',
data: formdatas,
contentType: false,
processData: false
})
.done(function(response) {
//show result
if (response.status == 'OK') {
} else if (response.status == 'FAIL') {
} else {
//show default message
}
})
.fail(function(jqXHR) {
if (jqXHR.status == 403) {
window.location = '/';
} else {
console.log(jqXHR);
}
});
});

yii2 Ajax Request Error 404

I want use ajax in yii2 (PHP framework)
I use the following code but it does not work.
My view file (PHP):
<script>
var url1='<?php echo Url::toRoute('Agehi/Ajaxshahr'); ?>';
</script>
<?php
$script= <<<JS
function selectshahr()
{
var ost = $("#ostan").val();
$.ajax(
{
type: "post",
url: url1,
data: ost,
cache: false,
success: function(data)
{
alert(data);
}
});
}
JS;
$this->registerJs($script,View::POS_BEGIN);
$form = ActiveForm::begin([
'id' => 'login-form',
'options' => ['class' => 'form-horizontal','enctype'=>'multipart/form-data'],
]);
echo $form->errorSummary($model,['header'=>'لطفا خطاهای زیر را برطرف نمایید','class'=>'']);
echo \vova07\imperavi\Widget::widget([
'selector' => '#content','name'=>'content',
'settings' => [
'lang' => 'fa',
'minHeight' => 200,
'plugins' => [
'clips',
'fullscreen'
]
]
]);
?>
<?= Html::label('استان','ostan',array()) ?>
<?= Html::dropDownList('ostan', null,
ArrayHelper::map($ostan, 'id', 'name'),array('class'=>'form-control','onchange'=>'selectshahr()','id'=>'ostan')) ?>
<?= Html::label('شهرستان/شهر','shahr',array()) ?>
<?= Html::dropDownList('shahr', null,
array(),array('class'=>'form-control')) ?>
and in my controller :
class AgehiController extends \yii\web\Controller
{
public function actionAjaxshahr($ostan)
{
$data = Shahr::findAll('condition', 'osid=' . $_POST['data']);
if(yii::$app->request->isAjax())
{
return $this->renderPartial('_Ajax_shahr', array('data' => $model));
}
return $this->renderPartial('_Ajax_shahr', array('data' => $model));
}
}
Everything seems okay but it does not respond to any request
I checked with Browser developer tools and it saw AJAX as a 404 error
Controller and action names in a route should be lowercase.

How to reload Zend Captcha image on click refresh button?

I apply a zend captcha in my php page now i require to add captcha reload button. Please give answer according to zend.
Just two quick snippets but I think you will get the idea. Adjust the element name and the selectors for your needs.
In your controller add a method to generate a fresh captcha
public function refreshAction()
{
$form = new Form_Contact();
$captcha = $form->getElement('captcha')->getCaptcha();
$data = array();
$data['id'] = $captcha->generate();
$data['src'] = $captcha->getImgUrl() .
$captcha->getId() .
$captcha->getSuffix();
$this->_helper->json($data);
}
In your view script (I'm using mootools for the ajax-request)
document.addEvent('domready', function() {
$$('#contactForm img').addEvent('click', function() {
var jsonRequest = new Request.JSON({
url: "<?= $this->url(array('controller' => 'contact', 'action' => 'refresh'), 'default', false) ?>",
onSuccess: function(captcha) {
$('captcha-id').set('value', captcha.id);
$$('#contactForm img').set('src', captcha.src);
}
}).get();
});
});
Edit: Added pahan's jquery
$(document).ready(function() {
$('#refreshcaptcha').click(function() {
$.ajax({
url: '/contact/refresh',
dataType:'json',
success: function(data) {
$('#contactForm img').attr('src', data.src);
$('#captcha-id').attr('value', data.id);
}
});
});
});
#user236501 Actually it can be any type of Zend Form Element (for example Button). You're even able to put clickable refresh link as Zend_Form_Element_Captcha description option like this:
$captcha = new Zend_Form_Element_Captcha('captcha', array(
'label' => 'Some text...',
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 6,
'timeout' => 300,
'font' => './fonts/Arial.ttf',
'imgDir' => './captcha/',
'imgUrl' => 'http://some_host/captcha/'
),
'description' => '<div id="refreshcaptcha">Refresh Captcha Image</div>'
));
but in that case Description decorator's options should be modified, for example:
$this->getElement('captcha')->getDecorator('Description')->setOptions(array(
'escape' => false,
'style' => 'cursor: pointer; color: #ED1C24',
'tag' => 'div'
));
It can be done in form's init() method.
Sorry for my english. Btw I'm not sure if I put my comment in the right place ;)
#Benjamin Cremer
thanks for the code, works like charm :)
after reading this
I did it using jquery.
$(document).ready(function() {
$('#refreshcaptcha').click(function() {
$.ajax({
url: '/contact/refresh',
dataType:'json',
success: function(data) {
$('#contactForm img').attr('src',data.src);
$('#captcha-id').attr('value',data.id);
}
});
});
});
In config/autoload/global.php add the following
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy','Zend\View\Strategy\PhpRendererStrategy'
),
),
in YourModule/src/YourModule create a new folder Ajax
Inside Yourmodule/Ajax create a file AjaxController.php
namespace YourModule\Ajax;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use YourModule\Forms\SignupForm;
class AjaxController extends AbstractActionController
{
public function refreshSignupCaptchaAction(){
$form = new SignupForm();
$captcha = $form->get('captcha')->getCaptcha();
$data = array();
$data['id'] = $captcha->generate();
$data['src'] = $captcha->getImgUrl().$captcha->getId().$captcha->getSuffix();
return new JsonModel($data);
}
}
Add route inside module.config.php
'yourmodule-ajax' =>array(
'type' => 'segment',
'options' => array(
'route' => '/yourmodule/ajax/:action',
'constraints' => array(
'action' => '\w+',
),
'defaults' => array(
'controller' => 'YourModule\Ajax\AjaxController',
)
),
),
last in your template, I assume you are using jquery
<div class="form-group">
<div id="captcha" class="control-group <?php echo count($form->get('captcha')->getMessages()) > 0 ? 'has-error' : '' ?>">
<?php echo $this->formLabel($form->get('captcha')); ?>
<div class="col-xs-12 col-sm-6">
<a id="refreshcaptcha" class="btn btn-default pull-right">Refresh</a>
<?php echo $this->formElement($form->get('captcha')); ?>
<?php echo $this->formElementErrors($form->get('captcha')); ?>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$('#refreshcaptcha').click(function() {
$.ajax({
url: '<?php echo $this->url('yourmodule-ajax', array('action'=>'refreshSignupCaptcha')) ?>',
dataType:'json',
success: function(data) {
$('#captcha img').attr('src', data.src);
$('#captcha input[type="hidden"]').attr('value', data.id);
$('#captcha input[type="text"]').focus();
}
});
return false;
});
});
</script>

Categories