Partial page reload using laravel and ajax - javascript

I am trying to submit a form using ajax so my page will not do a full page reload rather only the form should change to show any errors. I have tried many options from the web with no luck. This here is the best help I have seen, but it doesn't give the solution. Note I am using laravel version 5.3.10.
Here is my code:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$('#footer-form').click(function () {
//event.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost/ensignhospital/mail',
data: $('form#footer-form').serialize(),
dataType: 'html'
})
.done(function (data) {
console.log(data);
});
});
});
</script>
Laravel Route:
Route::group(['before' => 'guest'], function () {
/*
* CSRF Protection
*
* */
Route::group(['before' => 'csrf'], function () {
Route::post('/ensignhospital/mail', [
'as' => 'mail',
'uses' => 'HomeController#postSendMail'
]);
});
});
Laravel controller:
public function postSendMail(Request $request)
{
if($request->ajax()){
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'message' => 'required',
'g-recaptcha-response' => 'required|captcha'
]);
if($validator->fails()){
return redirect()->back()
->withErrors($validator)
->withInput(Input::all());
}else{
return View('passed');
}
}else{
return View('fail');
}
}
Form:
{!! Form::open(['route' => 'mail', 'method' => 'post', 'role' => 'form', 'id' => 'footer-form']) !!}
<div class="form-group has-feedback">
{!! Form::label('first_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder' => 'First Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('first_name'))
{{ $errors->first('first_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('last_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder' => 'Last Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('last_name'))
{{ $errors->first('last_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('email', null, ['class' => 'sr-only']) !!}
{!! Form::email('email', null, ['class' => 'form-control', 'placeholder' => 'Email address']) !!}
<i class="fa fa-envelope form-control-feedback"></i>
#if($errors->has('email'))
{{ $errors->first('email') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('message', null, ['class' => 'sr-only']) !!}
{!! Form::textarea('message', null, ['class' => 'form-control', 'rows' => 8, 'placeholder' => 'Message']) !!}
<i class="fa fa-pencil form-control-feedback"></i>
#if($errors->has('message'))
{{ $errors->first('message') }}
#endif
</div>
{!! Form::submit('Send', ['class' => 'btn btn-default', 'id' => 'mail_btn']) !!}
{!! Form::close() !!}

What you need to do is to render the view that you want to pass throught the ajax like this:
return view('passed')->render();
...
return view('fail')->render();
EDIT
You have to pass event as a clouser parameter and uncomment this: //event.preventDefault();:
$('#footer-form').click(function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost/ensignhospital/mail',
data: $('form#footer-form').serialize(),
dataType: 'html'
})
.done(function (data) {
console.log(data);
});
});
so that:
click(function () {
why it doesn't work. Should be:
click(function (event) {

Related

Yii2 How to remove selected value from Select2 of a dynamic form?

I created a dynamic form using wbraganca / yii2-dynamicform to handle requests in my solution. I have couple fields like Item, Qty and Unit. I have a list of items loaded using ArrayHelper and I am using Kartik's Select2 widget to load the data.
_form.php
<?php
use backend\models\Item;
use backend\models\ItemCategory;
use backend\models\ItemUnit;
use backend\models\Jobs;
use common\models\User;
use kartik\depdrop\DepDrop;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use yii\helpers\Url;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model backend\models\Requests */
/* #var $form yii\widgets\ActiveForm */
$js = '
jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
var i = index;
});
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
});
});
';
$this->registerJs($js);
$itemCategory = ItemCategory::find()->where(['cat_status' => 'Active'])->all();
$catData = ArrayHelper::map($itemCategory, 'cat_id', 'cat_name');
if (!Yii::$app->user->identity->isAdmin) {
$modelJobs = Jobs::find()
->joinWith('myJobs')
->where(['ja_user_id' => Yii::$app->user->id, 'ja_status' => 'Active'])
->all();
} else {
$modelJobs = Jobs::find()
->where(['job_status' => 'In Progress'])
->all();
}
$jobs = ArrayHelper::map($modelJobs, 'job_id', function ($modelJobs) {
return $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
});
if (isset($_GET['cid'])) {
$cat_id = $_GET['cid'];
$subCate = Item::find()->where(['item_category' => $cat_id, 'item_status' => 'Active'])->all();
$invListData = ArrayHelper::map($subCate, 'item_id', 'item_title');
} else {
$cat_id = '';
$invListData = [];
}
if (isset($_GET['job']) && $_GET['job'] != null) {
$job_id = $_GET['job'];
$modelJobs = Jobs::find()->where(['job_id' => $job_id])->one();
$job = $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
} else {
$job_id = '';
}
$modelUnit = ItemUnit::find()->where(['unit_status' => 'Active'])->all();
$unit = ArrayHelper::map($modelUnit, 'unit_id', function ($modelUnit) {
return $modelUnit->unit_name . '(' . $modelUnit->unit_short_name . ')';
});
?>
<div class="requests-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?php $form->errorSummary($model); ?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($model, 'rq_cat_type')->widget(Select2::class, [
'data' => $catData,
'options' => ['placeholder' => '--Select Material Category--', 'value' => $cat_id, 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
"select2:select" => "function(params) {
console.log($(this).val());
window.history.pushState('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
window.location.replace('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
jQuery.pjax.reload({ container: '#loaderPjax', async: false });
}",
],
]);
?>
</div>
<div class="col-md-4">
<?php if (isset($_GET['job']) && $_GET['job'] != null) { ?>
<?= $form->field($model, "rq_job_no")->dropDownList([$job_id => $job], ['value' => $job_id]) ?>
<?php } else { ?>
<?php echo $form->field($model, 'rq_job_no')->widget(Select2::class, [
'data' => $jobs,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?php } ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_req_date')->widget(\yii\jui\DatePicker::class, [
//'language' => 'ru',
'dateFormat' => 'php:Y-m-d',
'clientOptions' => [
'changeMonth' => true,
'changeYear' => true,
'showButtonPanel' => true,
'yearRange' => '1990:2030',
'minDate' => date('Y-m-d'),
],
'options' => ['class' => 'form-control', 'readOnly' => true, 'placeholder' => 'Enter the Item Required Date'],
]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_priority_type')->dropDownList(['Urgent' => 'Urgent', 'Normal' => 'Normal'], ['prompt' => '--Select Priority Type--']) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_approval_type')->dropDownList([1 => 'Aramco Approved Vendor Needed', 2 => 'Approved Aramco Submitted Needed', 3 => 'Warranty Certificate to be Collected', 4 => 'Long Lead Material',], ['prompt' => '--Select Type of Approval--']) ?>
</div>
</div>
<!-- code for dynamic form -->
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Request Items</h4>
</div>
<?php Pjax::begin(['id' => 'loaderPjax']); ?>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'rt_item',
'rt_qty',
'rt_unit',
],
]); ?>
<div class="container-items">
<!-- widgetContainer -->
<?php foreach ($modelsAddress as $i => $modelAddress) { ?>
<div class="item panel panel-default">
<!-- widgetBody -->
<div class="panel-heading">
<h4 class="panel-title pull-left"></h4>
<span class="panel-title-address"></span>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="fa fa-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="fa fa-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (!$modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]rt_id");
}
?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'reqItem form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_qty")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true, 'readOnly' => 'true']) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php } ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
<?php Pjax::end(); ?>
</div>
<div class="col-md-12">
<?= $form->field($model, 'rq_remarks')->textarea(['rows' => 6]) ?>
</div>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script>
$(document).on("change", ".reqItem", function() {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url": "units",
"type": "post",
"data": {
itemID: itemVal
},
success: function(data) {
console.log(data);
console.log(attrID);
$("#reqitems-" + attrID + "-rt_unit").val(data);
},
error: function(errormessage) {
//do something else
alert("not working");
}
});
});
</script>
The form is working perfectly, But I am facing some issues with the new requirement. The updated is to remove the selected value from the list. Which means if I select a value from the dropdown, the list should be updated without the selected value for next index in the dynamic form.
Tried couple of solutions with JQuery and javascript. The goal of requirement is to avoid duplicate entry of same value. Can anyone help me on this?

Yii2 - yii\grid\CheckboxColumn - Bulk Update and insert selected rows into another table

I have a table with these fields:
aca_class_subjects:
class_subject_id, class_subject_subject_id,
class_subject_class_group_id, class_subject_class_id
class_subject_id is the Primary Key and it is auto_increment.
class_subject_class_id and class_subject_class_group_id form a dependent dropdownlist.
class_subject_subject_id is from a table called aca_subjects and it will form the checkbox.
Controller: AcaClassSubjectsController
public function actionCreate()
{
$model = new AcaClassSubjects();
$searchModel = new AcaSubjectsSearch();
$searchModel->is_status = 0 ;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('create', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=> $model,
]);
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->class_subject_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
Model: AcaClassSubjects
public function attributeLabels()
{
return [
'class_subject_id' => Yii::t('aca', 'ID'),
'class_subject_subject_id' => Yii::t('aca', 'Subject'),
'class_subject_class_id' => Yii::t('aca', 'Class'),
'class_subject_class_group_id' => Yii::t('aca', 'Class Group'),
];
}
AcaSubjectsSearch
public function search($params)
{
$query = AcaSubjects::find()->where(['<>', 'is_status', 2]);
$dataProvider = new ActiveDataProvider([
'query' => $query, 'sort'=> ['defaultOrder' => ['subject_id'=>SORT_DESC]],
'pagination' => [ 'pageSize' => 5 ]
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'subject_id' => $this->subject_id,
]);
$query->andFilterWhere(['like', 'subject_name', $this->subject_name])
->andFilterWhere(['like', 'subject_code', $this->subject_code]);
return $dataProvider;
}
View
<div class="col-xs-12" style="padding-top: 10px;">
<div class="box">
<?php $form = ActiveForm::begin([
'id' => 'academic-level-form',
'enableAjaxValidation' => false,
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]); ?>
<div class="col-xs-12 col-lg-12 no-padding">
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(),'class_group_id','class_group_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class Group ---',
'onchange'=>'
$.get( "'.Url::toRoute('dependent/getclassmaster').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'class_subject_class_id').'" ).html( data );
}
);'
],
// 'disabled'=>'true',
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]),'class_id','class_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class ---'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
</div>
<div class="box-body table-responsive">
<h4><strong><u>Select Subject(s)</u></strong></h4>
<div class="course-master-index">
<?= GridView::widget([
'id'=>'grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'header' => Html::checkBox('selection_all', false, [
'class' => 'select-on-check-all',
'label' => 'All',
]),
'visible'=> true,
'contentOptions' =>['style' => 'vertical-align:middle;width:30px'],
'checkboxOptions' => function($model, $key, $index, $column) {
return ['value' => $model->subject_id];
}
],
['class' => 'yii\grid\SerialColumn'],
// 'id',
'subject_name',
],
]); ?>
<?= Html::input('hidden','keylists',$value='', $options=['id'=>'keylist']) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' =>'btn btn-success btn-block btn-lg','id'=>"button123"]) ?>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
My questions are
After selecting particular rows (subject_id) using checkboxes from Table aca_subjects, and also select the dropdownlist as shown in the diagram
How do I insert them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
How do I update them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
How do I display a dialogue box when nothing is selected?
Note: class_subject_subject_id (checkbox in gridview),class_subject_class_id (dropdownlist), class_subject_class_group_id (dropdownlist)
When I clicked on submit, nothing goes to the database
Well, the question is a bit broad as you haven't shown any code related to solving your problem specifically so my wild guess is that you have a basic showstopper for collecting the class_subject_subject_id from the gridview. so i will suggest the javascript part in my answer where it submits the form with ajax.
But before i suggest you a solution you have a basic problem that you are wrapping the gridview with the form you are using to insert the subjects in the aca_class_subjects
Why?
Because if you wrap the Gridview with a form along with the gridview filters the GridView does not create its own hidden form that it uses for submitting the filter inputs for search in the GridView, and hence when you will try search by typing in the GridView filter input it would submit it to the action specified in your outer form that can have a different action like in your case.
So if you still want to use the ActiveForm do not wrap the Gridview inside the form keep it separate, and close it before you call the GridView::widget() but you have the button placed in the end of the Gridview and you dont want to change the design so change the code for the button from Html::submitButton() to Html::button() and keep it outside the ActiveForm that you have created. You can submit the form with javascript.
So your view code should look like below
<div class="col-xs-12" style="padding-top: 10px;">
<div class="box">
<?php
$form = ActiveForm::begin([
'id' => 'academic-level-form',
'enableAjaxValidation' => false,
'action'=>\yii\helpers\Url::to(['assign-subjects'])
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]);
?>
<div class="col-xs-12 col-lg-12 no-padding">
<div class="col-xs-12 col-sm-6 col-lg-6">
<?=
$form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(), 'class_group_id', 'class_group_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class Group ---',
'onchange' => '
$.get( "' . Url::toRoute('dependent/getclassmaster') . '", { id: $(this).val() } )
.done(function( data ) {
$( "#' . Html::getInputId($model, 'class_subject_class_id') . '" ).html( data );
}
);'
],
// 'disabled'=>'true',
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?=
$form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]), 'class_id', 'class_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class ---'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
</div>
<?=Html::input('hidden', 'keylists', $value = '', $options = ['id' => 'keylist']) ?>
<?php ActiveForm::end(); ?>
<div class="box-body table-responsive">
<h4><strong><u>Select Subject(s)</u></strong></h4>
<div class="course-master-index">
<?=
GridView::widget([
'id' => 'grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'header' => Html::checkBox('selection_all', false, [
'class' => 'select-on-check-all',
'label' => 'All',
]),
'visible' => true,
'contentOptions' => ['style' => 'vertical-align:middle;width:30px'],
'checkboxOptions' => function($model, $key, $index, $column){
return ['value' => $model->subject_id];
}
],
['class' => 'yii\grid\SerialColumn'],
// 'id',
'subject_name',
],
]);
?>
<div class="form-group">
<?=Html::button('Submit', ['class' => 'btn btn-success btn-block btn-lg', 'id' => "button123"]) ?>
</div>
</div>
</div>
</div>
</div>
Now about the saving of the records.
You can get all the selected subjects that are in the grid view by using the following javascript code where you select all the checked checkboxes which have the name selection[]. Add the below code on top of your view
$reflect = new ReflectionClass($model);
$subjectId = $reflect->getShortName() . '[class_subject_subject_id][]';
$js = <<<JS
$("#button123").on('click',function(e){
e.preventDefault();
$("#academic-level-form").yiiActiveForm('submitForm');
});
$("#academic-level-form").on('beforeSubmit',function(e){
e.preventDefault();
// yii.getCsrfParam(),yii.getCsrfToken(),
let subjects=$("input[name='selection[]']:checked");
let subjectsSelected=subjects.length;
if(!subjectsSelected){
alert('select some subjects first');
}else{
let data=$(this).serializeArray();
$.each(subjects,function(index,elem){
data.push({name:"$subjectId",value:$(elem).val()})
});
let url=$(this).attr('action');
$.ajax({
url:url,
data:data,
type:'POST',
}).done(function(data){
alert(data);
}).fail(function(jqxhr,text,error){
alert(error);
});
}
return false;
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Now if you have print_r(Yii::$app->request->post()) inside the actionAssignSubjects() in your controller where the form is submitting you can see the output of the posted variables and your subjects will be under the same model array that you are using for populating the dropdowns with the name class_subject_subject_id and all the selected subjects would be under this array. You can loop over them to save to your desired model.
I leave the rest of the work on you to do by your self and if you run into any problems you should post a separate question with the targetted code.

Catching element by ID when it's defined with twig

I've created some elements with php in order to made up a form. This is the snippet of PHP code:
$builder->add('path', FileType::class, array('label' => 'Submit', 'attr' => array('class' => 'style-1 btn_upload_pdf_php js-btn_upload_pdf', 'id' => 'pdf')));
$builder->add('title', TextType::class, array('label' => 'Flyer\'s name', 'attr' => array('class' => 'style-1 name_pdf js-name_pdf', 'placeholder' => 'Nome del volantino')));
$builder->add('expirationData', DateType::class, array('label' => 'scadenza', 'attr' => array('class' => 'style-1 deadline_pdf js-deadline_pdf', 'placeholder' => 'Nome del volantino', 'id' => 'deadline_pdf')));
I've tried to set path's ID by twig with the following statement:
{{ form_widget(form1.path, { 'id': 'pdf'}) }}
But when I try to get element ($('#pdf')) via JavaScript, it doesn't work. It seems that the element isn't created.
Thx.
to pass id to twig form, you have to do it like that :
{{ form_widget(form1.path, {'attr': {'id': 'pdf'}}) }}

Html datalist values from array from controller

I'm trying to make an input in HTML that when you write something it show you some possibilities. This possibilities are sent by my controller with an array.
This is my view:
<div class="form-group">
{!!Form::label('marca','Marca: ')!!}
{!!Form::text('marca',null, ['id' => 'marca', 'class' => 'form-control', 'onkeyup'=>'javascript:this.value=this.value.toUpperCase();', 'list'=>'lista'])!!}
<datalist id="lista"></datalist>
<br>
{!!Form::label('modelo','Modelo: ')!!}
{!!Form::text('modelo',null, ['id' => 'modelo', 'class' => 'form-control', 'placeholder' => 'Ingresa el modelo'])!!}
<br>
{!!Form::label('part_number','Part Number: ')!!}
{!!Form::text('part_number',null, ['id' => 'pn', 'class' => 'form-control', 'placeholder' => 'Ingresa el part number','onkeyup'=>'javascript:this.value=this.value.toUpperCase();'])!!}
<br>
{!!Form::label('coste','Coste: ')!!}
{!!Form::number('coste',null, ['id' => 'coste', 'step'=>'any', 'class' => 'form-control', 'placeholder' => 'Ingresa el coste del equipo'])!!}
<br>
{!!Form::label('caracteristicas','Características: ')!!}
{!!Form::text('caracteristicas',null, ['id' => 'caract', 'class' => 'form-control', 'placeholder' => 'Ingresa las características necesarias del part number'])!!}
</div>
<script type="text/javascript">
var marcas = $array;
var list = document.getElementById('lista');
marcas.forEach(function(item){
var option = document.createElement('option');
option.value = item;
list.appendChild(option);
});
This is my Controller:
public function create()
{
$marcas = Modelos::Marcas();
$array = array();
foreach ($marcas as $marca) {
$array[] = $marca->marca;
}
return view('modelos.create',compact('array'));
}
The console gives me the following error:
{Uncaught ReferenceError: $array is not defined at create:241}

Show success/error message on dropzone file upload

I am using dropzone file upload, when I return success / error from controller, how do I show it on my view file..
View file ,
<div class="box-body">
#if ( $errors->count() > 0 )
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{{ $message = 'Please select csv file only.' }}
</div>
#endif
{!! Form::open([ 'url' => 'admin/reports','class' => 'dropzone', 'id' => 'reportfile' ]) !!}
{!! csrf_field() !!}
<div class="col-md-12">
<h3 style="text-align : center">Select File</h3>
</div>
<button type="submit" class="btn btn-primary">Upload Report</button>
{!! Form::close() !!}
</div>
Controller Code
if ($request->hasFile('file')) {
$file = Input::file('file');
$validator = Validator::make(
[
'file' => $file,
'extension' => strtolower($file->getClientOriginalExtension()),
], [
'file' => 'required',
'extension' => 'required|in:csv',
]
);
if ($validator->fails()) {
return Response::json('error', 400);
}
JS Code
<script>
window.onload = function () {
Dropzone.options.reportfile = {
paramName: "file",
maxFilesize: 2,
error: function (file, response) {
alert('hiii')
},
init: function () {
this.on("addedfile", function (file) {
alert("Added file.");
});
},
accept: function (file, done) {
alert('hi')
if (file.name == "justinbieber.jpg") {
done("Naha, you don't.");
}
}
};
};
</script>
Not even alert is working...any help is much appreciated..Thanks
You should listen the events, and trigger whether it is success or not
Dropzone.options.uploadWidget = {
init: function() {
this.on('success', function( file, resp ){
alert("Success");
});
},
...
};
Note : You can have the other breakpoints as suggested here

Categories

Resources