I'm using Form Repeater in a simple HTML page, when I send the form, I only get the first values (First line).
HTML:
<div id="kt_repeater_1">
<div class="form-group row" id="kt_repeater_1">
<div data-repeater-list="product_list" class="col-lg-12">
<div data-repeater-item class="form-group row">
<div class="col-md-9">
<label>Produit:</label>
<select class="form-control selectpicker" name="product">
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
</select>
<div class="d-md-none mb-2"></div>
</div>
<div class="col-md-2">
<label>Qte:</label>
<input type="text" name="qty" class="form-control" />
<div class="d-md-none mb-2"></div>
</div>
<div class="col-md-1">
<a href="javascript:;" data-repeater-delete="" style="margin-top: 25px;" class="btn btn-sm font-weight-bolder btn-light-danger">
<i class="la la-trash-o"></i>
</a>
</div>
</div>
</div>
</div>
<div class="form-group row" style="margin-top: -20px;">
<label class="col-lg-2 col-form-label text-right"></label>
<div class="col-lg-12">
<a href="javascript:;" data-repeater-create="" class="btn btn-sm font-weight-bolder btn-light-primary">
<i class="la la-plus"></i>Add Product
</a>
</div>
</div>
</div>
JS:
var KTFormRepeater = function() {
// Private functions
var demo1 = function() {
$('#kt_repeater_1').repeater({
initEmpty: false,
defaultValues: {
},
show: function() {
$(this).slideDown();
},
hide: function(deleteElement) {
$(this).slideUp(deleteElement);
},
});
}
return {
// public functions
init: function() {
demo1();
}
};
}();
$(document).ready(function() {
KTFormRepeater.init();
});
PHP when I print_r($_POST[]) AND send 2 Lines
(Product 1, QTY: 10 - Product 1, QTY: 20):
"product_list":[{"product":"1","qty":"10"}]
Can anyone help me with this, please?
correct :
name="product[0][qty]"
not correct
name="qty"
I am a little late here but I am uploading a complete solution to how to add form repeater in your page if you are using metronic keen theme version 8.*.
< script >
var hostUrl = "assets/"; < /script> <
script src = "{{ asset('assets/Metronic-Theme/plugins/global/plugins.bundle.js') }}" > < /script> <
script src = "{{ asset('assets/Metronic-Theme/js/scripts.bundle.js') }}" > < /script> <
script src = "{{asset('assets/Metronic-Theme/plugins/custom/prismjs/prismjs.bundle.js')}}" > < /script> <
script src = "{{asset('assets/Metronic-Theme/plugins/custom/formrepeater/formrepeater.bundle.js')}}" > < /script> <
script src = "{{asset('assets/Metronic-Theme/js/custom/documentation/documentation.js')}}" > < /script> <
script src = "{{asset('assets/Metronic-Theme/js/custom/documentation/search.js')}}" > < /script>
<
script >
"use strict";
var KTFormRepeaterBasic = {
init: function() {
$("#kt_docs_repeater_basic").repeater({
initEmpty: !1,
defaultValues: {
"text-input": "foo"
},
show: function() {
$(this).slideDown()
},
hide: function(t) {
$(this).slideUp(t)
}
})
}
};
KTUtil.onDOMContentLoaded((function() {
KTFormRepeaterBasic.init()
}));
<
/script>
<link href="{{ asset('assets/Metronic-Theme/plugins/custom/datatables/datatables.bundle.css') }}" rel="stylesheet" type="text/css" /><link href="{{ asset('assets/Metronic-Theme/plugins/global/plugins.bundle.css') }}" rel="stylesheet" type="text/css" /><link href="{{ asset('assets/Metronic-Theme/css/style.bundle.css') }}" rel="stylesheet" type="text/css" />
<!--begin::Repeater-->
<div id="kt_docs_repeater_basic">
<!--begin::Form group-->
<div class="form-group">
<div data-repeater-list="kt_docs_repeater_basic">
<div data-repeater-item>
<div class="form-group row">
<div class="col-md-3">
<label class="form-label">Accessory</label> {{-- <input type="email" class="form-control mb-2 mb-md-0" placeholder="Enter full name" name="name1" id="check1" /> --}}
<select class="form-control mb-2 mb-md-0" placeholder="Select Accesory" id="sel1" name="accessory">
<option value="" disabled selected>Select Accessory</option>
#foreach ($shop->getCrmSetting('Accessory',$shop->id) as $item)
<option>{{$item->accessory}}</option>
#endforeach
</select>
</div>
<div class="col-md-3">
<label class="form-label">Accessory Serial Number</label>
<input type="text" class="form-control mb-2 mb-md-0" placeholder="Enter Accessory Serial Number" name="accessoryserialno" />
</div>
<div class="col-md-4">
<a href="javascript:;" data-repeater-delete class="btn btn-sm btn-light-danger mt-3 mt-md-8">
<i class="la la-trash-o"></i>Delete
</a>
</div>
</div>
</div>
</div>
</div>
<!--end::Form group-->
<!--begin::Form group-->
<div class="form-group mt-5">
<a href="javascript:;" data-repeater-create class="btn btn-light-primary">
<i class="la la-plus"></i>Add
</a>
</div>
<!--end::Form group-->
</div>
<!--end::Repeater-->
and now the code from backened server
just to tell how you can retrieve data.
Remember to add name="" attribute to html element to retrieve data in backend server.as i have added it to select and input elements.
foreach ($request->kt_docs_repeater_basic as $key => $value) {
CustomerAccessory::create([
'order_id' => $order->id,
'accessory' => $value['accessory'],
'accessoryserialno' => $value['accessoryserialno'],
]);
}
this project is in laravel so code is from controller.
In this way you can loop through the form repeater
and then can store and use the values any way you like in the backend.
You can make changes according to your theme and layout.
but you have to add the form repeater scripts and css and jquery.
and if you only want to use first row from foreach you can either put a break statement or you can do this.
$request->kt_docs_repeater_basic[0]['accessory'];
$request->kt_docs_repeater_basic[0]['accessoryserialno'];
or
foreach ($request->kt_docs_repeater_basic as $key => $value) {
CustomerAccessory::create([
'order_id' => $order->id,
'accessory' => $value['accessory'],
'accessoryserialno' => $value['accessoryserialno'],
]);
break;
}
Related
good afternoon everyone. I'm making a form to edit leave allocation data with jquery ajax. the form consists of (id_kategoricuti, id_karyawan,durasi, mode_alokasi, tgl_masuk, tgl_sekarang, aktif_dari, sampai).
Previously in from create, the conditions are:
when id_kategoricuti is selected, the form durasi, mode_alokasi will be filled in automatically using ajax.
For example, in the selected id_kategoricuti id form Cuti Tahunan, the tgl_masuk and tgl_sekarang forms will appear.
then, when selecting id_karyawan, the tanggal_masuk form will automatically be filled according to the entry date data in the employee table. so that only the aktif_dari and sampai forms are filled in.
condition from edit leave allocation:
data appears according to the id that has been selected.
the user makes changes to the desired data.
save.
however, I'm facing a problem on this edit form:
because when I click on one of the data to edit, what appears on the form is only id_kategoricuti and id_karyawan.
the form mode_alokasi, durasi, aktif_dari and sampai are empty.
The form was only filled in when id_karyawan/id_kagotericuti was edited.
the data in the box below the category form is the data that should appear on the form.
This is the appearance of the leave allocation edit form before editing:
this is the appearance of the leave allocation edit form after the leave id_categories are edited:
my Controller:
public function getTglmasuk(Request $request)
{
try {
$getTglmasuk = Karyawan::select('tglmasuk')
->where('id','=',$request->id_karyawan)->first();
// dd($request->id_karyawan,$getTglmasuk);
if(!$getTglmasuk) {
throw new \Exception('Data not found');
}
return response()->json($getTglmasuk,200);
} catch (\Exception $e){
return response()->json([
'message' =>$e->getMessage()
], 500);
}
}
public function getSettingalokasi(Request $request)
{
try {
$getSettingalokasi=Settingalokasi::select('id','id_jeniscuti','durasi','mode_alokasi')
->where('id_jeniscuti','=',$request->id_jeniscuti)->first();
if(!$getSettingalokasi) {
throw new \Exception('Data not found');
}
return response()->json($getSettingalokasi,200);
} catch (\Exception $e){
return response()->json([
'message' =>$e->getMessage()
], 500);
}
}
my Editalokasi.blade.php:
{{-- FORM SETTING ALOKASI--}}
<div class="modal fade" id="editalokasi{{$data->id}}" tabindex="-1" role="dialog" aria-
labelledby="editalokasi" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true">×</button>
<h4 class="modal-title" id="editalokasi">Edit Alokasi Cuti</h4>
</div>
<div class="modal-body">
<form class="input" action="/updatealokasi/{{$data->id}}" method="POST"
enctype="multipart/form-data">
#csrf
#method('POST')
<div class="panel-body">
<div class="col-md-6">
<div class="form-group col-sm">
<label for="id_jeniscuti" class="col-form-label">Kategori
Cuti</label>
<select name="id_jeniscuti" id="idjeniscuti" class="form-control">
<option value="{{$data->id_jeniscuti}}" selected>
{{$data->jeniscutis->jenis_cuti}}
</option>
#foreach ($jeniscuti as $jenis)
<option value="{{$jenis->id }}">{{ $jenis->jenis_cuti }}
</option>
#endforeach
</select>
</div>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idsettingalokasi" value="{{$data-
>id_settingalokasi}} --> id settingalokasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->id_jeniscuti}}
--> id kategori" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->id_karyawan}} -
->id karyawan" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->durasi}} Hari
--> durasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->mode_alokasi}}
-->mode alokasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="
{{\Carbon\carbon::parse($data->aktif_dari)->format('m/d/Y')}} --
>aktif dari" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="
{{\Carbon\carbon::parse($data->sampai)->format('m/d/Y')}} -->sampai tanggal"readonly>
<div class="form-group col-sm" id="idkaryawan">
<label for="id_karyawan" class="col-form-label">Karyawan</label>
<select name="id_karyawan" id="id_karyawan" class="form-control">
<option value="{{$data->id_karyawan}}" selected>{{$data->karyawans->nama}}</option>
#foreach ($karyawan as $data)
<option value="{{ $data->id }}">{{ $data->nama }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="durasi" class="col-form-label">Durasi (Hari)</label>
<input type="text" class="form-control" name="durasi" placeholder="durasi" id="duration" value="{{$data->durasi}}" readonly>
</div>
<div class="form-group">
<label for="mode_alokasi" class="col-form-label">Mode Alokasi</label>
<input type="text" class="form-control" name="mode_alokasi" placeholder="mode alokasi" value="{{$data->mode_alokasi}}" id="modealokasi" readonly>
</div>
</div>
<div class="col-md-6">
<div class="" id="tglmulai">
<div class="form-group">
<label for="tgl_masuk" class="form-label">Tanggal Masuk</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="tglmasuk" name="tgl_masuk" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tglnow">
<div class="form-group">
<label for="tgl_sekarang" class="form-label">Tanggal Sekarang</label>
<div class="input-group">
<input type="text" class="form-control" id="tglsekarang" name="tgl_sekarang" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalmulai">
<div class="form-group">
<label for="tgl_mulai" class="form-label">Aktif Dari</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea3" name="aktif_dari" value="{{\Carbon\carbon::parse($data->aktif_dari)->format('m/d/Y')}}" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalselesai">
<div class="form-group">
<label for="sampai" class="form-label">Sampai</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea4" name="sampai" value="{{\Carbon\carbon::parse($data->sampai)->format('m/d/Y')}}" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" name="submit" value="save">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/app.js"></script>
<script src="assets/pages/form-advanced.js"></script>
my Javascript:
<!-- script to fetch data settingalokasi from table settingalokasi -->
<script>
$('#idjeniscuti').on('change',function(e){
var id_jeniscuti = e.target.value;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
type:"POST",
url: '{{route('get.Setting.alokasi')}}',
data: {'id_jeniscuti':id_jeniscuti},
success:function(data){
// console.log(data);
$('#idsettingalokasi').val(data.id);
$('#duration').val(data.durasi);
$('#modealokasi').val(data.mode_alokasi);
}
});
});
</script>
<!-- script to fetch data tanggal_masuk from table karyawan-->
<script>
$('#id_karyawan').on('change',function(e){
var id_karyawan = e.target.value;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
type:"POST",
url: '{{route('get.Tanggalmasuk')}}',
data: {'id_karyawan':id_karyawan},
success:function(data){
// console.log(data);
$('#tgl_masuk').val(data.tglmasuk);
// console.log(data?.tglmasuk)
}
});
});
</script>
<script type="text/javascript">
$(function()
{
$('#tglmulai').prop("hidden", true);
$('#tglnow').prop("hidden", true);
$('#jenicuti').on('change', function(a)
{
if(a.target.value == 1)
{
$('#tglmulai').prop("hidden", false);
$('#tglnow').prop("hidden", false);
} else
{
$('#tglmulai').prop("hidden", true);
$('#tglnow').prop("hidden", true);
}
});
});
</script>
this is my first time using JQUERY AJAX for AUTOFILL. can anyone help me to solve this problem?
I am trying to submit form data using Ajax, but I am getting the error message. I am unable to find the error.
Little heads up- I am using Sweet Alert to display success or error message
Here is the Controller Code -
class NewUserRegnController extends Controller
{
public function submitNewRegn(Request $request){
$first_name = $request->first_name;
$last_name = $request->last_name;
$email = $request->email;
$password = Hash::make($request->password, [
'memory' => '1024',
'time' => '2',
'threar' => '2',
]);
// $confirm_password = $request->confirm_password;
$mobno = $request->mobno;
$dob = $request->dob;
$gender = $request->gender;
$address = $request->address;
$country = $request->country;
date_default_timezone_set("Asia/Kolkata");
$time = date("Y-m-d,H:i:s ");
// $users = new Newuser();
// $users->first_name = $first_name;
// $users->last_name = $last_name;
// $users->email = $email;
// $users->password = $password;
// $users->mobno = $mobno;
// $users->dob = $dob;
// $users->gender = $gender;
// $users->address = $address;
// $users->country = $country;
// $users->TIME_STAMP = $time;
// $users->save();
$act = "INSERT";
DB::select('CALL my_stored_procedures(?,?,?,?,?,?,?,?,?,?,?,?)', array($act,0,$first_name,$last_name,$email,$password,$mobno,$dob,$gender,$address,$country,$time));
and the Blade-
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<!-- Ajax script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<!-- Sweet Alert -->
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</head>
<body>
<!-- Navigation Bar -->
<div class="container-fluid">
<div class="row">
<div class="col">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark navbar-fixed-top">
<a class="navbar-brand" href="index">User Info</a>
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact Us</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right ">
<li class="nav-item"><a class="nav-link" href="new_user"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
<li class="nav-item"><a class="nav-link" href="login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</nav>
</div>
</div>
<div class="text-center pt-3">
<p style="color:red">For safety,Do Not hit the back button or refresh the page</p>
<p style="color:red">Use the buttons given in the form below</p>
</div>
<form class="form-group" id="new_user_form" method="post" onsubmit="sendForm()" autocomplete="off">
<div class="row m-5 p-5 bg-warning text-white">
<div class="col">
<div class="form-group">
#csrf
<label for="fname">First Name:</label>
<input type="text" class="form-control" name="first_name" value="{{$first_name}}" readonly >
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" name="last_name" value="{{$last_name}}" readonly>
</div>
<div class="form-group">
<label for="email">Email/Username:</label>
<input type="text" class="form-control" name="email" value="{{$email}}" readonly>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="password" value="{{$password}}" readonly>
</div>
<div class="form-group">
<label for="mobno">Mobile Number:</label>
<input type="text" class="form-control" name="mobno" value="{{$mobno}}" readonly>
</div>
<div class="form-group">
<label for="dob">Date of Birth(in YYYY-MM-DD):</label>
<input type="text" class="form-control" name="dob" value="{{$dob}}" readonly>
</div>
<div class="form-group">
<label for="gender">Gender:</label>
<input type="text" class="form-control" name="gender" value="{{$gender}}" readonly>
</div>
<div class="form-group">
<label for="address">Address:</label>
<textarea class="form-control" rows="5" name="address" readonly>{{$address}}</textarea>
</div>
<div class="form-group">
<label for="country">Country:</label>
<input name="country" class="form-control" id="countrylist" value="{{$country}}" readonly>
</div>
<div class="form-group">
<label for="dt">Date and Time of Submission:</label>
<input type="text" class="form-control" name="dt" value=#php date_default_timezone_set("Asia/Kolkata"); echo date("Y-m-d,H:i:s ") #endphp readonly>
</div>
<div class="form-group text-center">
<!-- <a href="{{url('recheck_form')}}"/><button type="submit" class="btn btn-primary mb-2 text-center" onclick="store_using_ajax()">Submit</button> -->
<input type="submit" class="btn btn-primary mb-2 text-center" id="submit_form">
</div>
<div class="form-group text-center ">
<button type="button" class="btn btn-danger">Cancel</button>
<button type="button" class="btn btn-warning ">Edit</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#new_user_form').on('submit',function sendForm(e){
e.preventDefault();
var fd = new FormData(myform );
var form_data = $(this);
$.ajax({
type:'POST',
url: "submit-form" ,
cache: false,
processData: false,
contentType: false,
data:fd,
data: $('#new_user_form').serialize(),
success:function(response){
swal({
title: "Form Submitted Successfully!",
text: "New User Registered !",
icon: "success",
button: "Okay",
})
},
error: function(response){
swal({
title: "Error in submitting form",
text: "Please refresh the page and try again! ",
icon: "warning",
button: "Okay",
});
}
});
});
});
</script>
The Routes -
Route::get('login','LoginController#loginuser');
Route::post('loggedinuser' , 'LoginController#loginvalidator' );
Route::get('new_user','NewUserController#getCountry');
Route::post('recheck-form', 'NewUserController#showdata');
Route::get('loginbackup',function(){
return view('login-backup');
});
Route::post('submit-form' , 'NewUserRegnController#submitNewRegn');
I tried changing the controller and function names,but that didnt help. Also,deleting cookies and clearing browser history do not work either.
First, I forgot to add some closing html tags. Once that was done, I needed to add the CSRF tokens in the ajax script as well as meta tag.
I re-edited the question with all the previously made mistakes to show where I did wrong.
Here are the codes to be added :-
Closing HTML Tags
</form> </body> </html>
Meta tag
<meta name="csrf-token" content="{{ csrf_token() }}">
Ajax Request Header setup in the Ajax Script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I have successfully loaded the supplied image to the storage in the public folder within the images folder via Dropzone js. I am unclear on how to upload the reference to my phpmyadmin SQL database. If I hard code it into the db, I can see it displayed on the page. However, with the form I am using, I am calling the component within my update tasks form. I am not sure if this is why it is not working but in any case, I will post the code in the hopes someone can orient me in the right direction. Thank you in advance.
ImageController.php
public function store(Request $request)
{
$imageName = time() . '.' . $request->file->getClientOriginalExtension();
$request->file->move(public_path('images'), $imageName);
return response()->json(['success' => 'You have successfully uploaded the file(s).']);
}
web.php
Route::post('store-multiple-image', 'ImageController#store');
app.js
Vue.component(
"multiple-image-component",
require("./components/MultipleImageUploadComponent.vue").default
);
TaskController.php (store method only for brevity)
public function store(Request $request)
{
// $this->validate($request, [
// 'name' => 'required|string|max:191',
// 'email' => 'required|string|email|max:191|unique:users',
// 'password' => 'required|string|min:6'
// ]);
return Task::create([
'task_name' => $request['task_name'],
'task_priority' => $request['task_priority'],
'task_assigned_to' => $request['task_assigned_to'],
'task_assigned_by' => $request['task_assigned_by'],
'task_description' => $request['task_description'],
'task_to_be_completed_date' => $request['task_to_be_completed_date'],
'task_status' => $request['task_status'],
'task_notes' => $request['task_notes'],
'task_finished' => $request['task_finished'],
'image' => $request['image'],
]);
}
Tasks.vue (I have included everything here just in case I am causing a conflict somewhere)
<template>
<div class="custom-container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card w-100">
<div class="card-header text-white" style="background-color: #605ca8;">
<h3 class="card-title">Tasks</h3>
<div class="card-tools">
<button class="btn btn-success" #click="newModal">
<i class="fas fa-tasks"></i> Add New Task
</button>
</div>
</div>
<!-- /.card-header -->
</div>
</div>
</div>
<div v-for="task in tasks" :key="task.id">
<div class="my-3 p-3 bg-white rounded box-shadow">
<div class="row">
<div class="col-md-4">
<h5>Task</h5>
<hr />
<p>{{ task.task_name }}</p>
</div>
<div class="col-md-4">
<h5>Priority</h5>
<hr />
<p>{{ task.task_priority }}</p>
</div>
<div class="col-md-4">
<h5>Assigned To</h5>
<hr />
<p>{{ task.task_assigned_to }}</p>
</div>
<div class="col-md-4">
<h5>Assigned By</h5>
<hr />
<p>{{ task.task_assigned_by }}</p>
</div>
<div class="col-md-4">
<h5>Date Assigned</h5>
<hr />
<p>{{ task.created_at }}</p>
</div>
<div class="col-md-4">
<h5>Due</h5>
<hr />
<p>{{ task.task_to_be_completed_date }}</p>
</div>
<div class="col-md-4">
<h5>Task Description</h5>
<hr />
<p>{{ task.task_description }}</p>
</div>
<div class="col-md-4">
<h5>Finished</h5>
<hr />
<p>{{ task.task_finished }}</p>
</div>
<div class="col-md-4">
<h5>Status</h5>
<hr />
<p>{{ task.task_status }}</p>
</div>
<div class="col-md-4">
<h5>Images</h5>
<hr />
<img style="max-width: 150px;" :src="'/images/' + task.image" alt />
<br />
<img style="max-width: 150px;" src="/img/molding.jpg" alt />
</div>
<div class="col-md-4">
<h5>Notes</h5>
<hr />
<p>{{ task.task_notes }}</p>
</div>
<div class="col-md-4">
<h5>Action</h5>
<hr />
<a href="#" class="badge badge-primary p-2 mb-3" #click="editModal(task)">
<i class="fa fa-edit"></i> Edit
</a>
<a #click="deleteTask(task.id)" href="#" class="badge badge-danger p-2">
<i class="fa fa-trash"></i> Delete
</a>
</div>
</div>
</div>
</div>
<form #submit.prevent="editmode ? updateTask() : createTask()">
<!-- Modal -->
<div
class="modal fade"
id="addNew"
tabindex="-1"
aria-labelledby="addNewLabel"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-show="!editmode" id="addNewLabel">Add New Task</h5>
<h5 class="modal-title" v-show="editmode" id="addNewLabel">Update Task Information</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<input
id="task_name"
type="text"
v-model="form.task_name"
name="task_name"
class="form-control"
placeholder="Task Name"
:class="{
'is-invalid': form.errors.has(
'task_name'
)
}"
/>
<has-error :form="form" field="task_name"></has-error>
</div>
<div class="form-group">
<select
id="task_priority"
type="text"
v-model="form.task_priority"
name="task_priority"
class="form-control"
:class="{
'is-invalid': form.errors.has(
'task_priority'
)
}"
>
<option value>Select a Priority Level</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<has-error :form="form" field="task_priority"></has-error>
</div>
<div class="form-group">
<textarea
id="task_description"
type="text"
v-model="form.task_description"
name="task_description"
class="form-control"
placeholder="Task Description"
:class="{
'is-invalid': form.errors.has(
'task_description'
)
}"
></textarea>
<has-error :form="form" field="task_description"></has-error>
</div>
<div class="form-group">
<input
id="task_assigned_by"
type="text"
v-model="form.task_assigned_by"
name="task_assigned_by"
class="form-control"
placeholder="Assigned By"
:class="{
'is-invalid': form.errors.has(
'task_assigned_by'
)
}"
/>
<has-error :form="form" field="task_assigned_by"></has-error>
</div>
<div class="form-group">
<input
id="task_assigned_to"
type="text"
v-model="form.task_assigned_to"
name="task_assigned_to"
class="form-control"
placeholder="Assigned To"
:class="{
'is-invalid': form.errors.has(
'task_assigned_to'
)
}"
value="form.user.id"
/>
<has-error :form="form" field="task_assigned_to"></has-error>
</div>
<div class="form-group">
<label for="task_to_be_completed_date">Due:</label>
<input
id="task_to_be_completed_date"
type="date"
v-model="form.task_to_be_completed_date"
name="task_to_be_completed_date"
class="form-control"
placeholder="Due: "
:class="{
'is-invalid': form.errors.has(
'task_to_be_completed_date'
)
}"
/>
<has-error :form="form" field="task_to_be_completed_date"></has-error>
</div>
<div class="form-group">
<select
id="task_status"
type="text"
v-model="form.task_status"
name="task_status"
class="form-control"
:class="{
'is-invalid': form.errors.has(
'task_status'
)
}"
>
<option value>Select Task Status</option>
<option value="Pending">Pending</option>
<option value="Finished">Finished</option>
<option value="Incomplete">Incomplete</option>
</select>
<has-error :form="form" field="task_status"></has-error>
</div>
<div class="form-group">
<select
id="task_finished"
type="text"
v-model="form.task_finished"
name="task_finished"
class="form-control"
:class="{
'is-invalid': form.errors.has(
'task_finished'
)
}"
>
<option value>Select finished status</option>
<option value="Finished">Finished</option>
<option value="Unfinished">Unfinished</option>
</select>
<has-error :form="form" field="task_status"></has-error>
</div>
<div class="form-group">
<label for="task_notes">Notes:</label>
<textarea
id="task_notes"
type="text"
v-model="form.task_notes"
name="task_notes"
class="form-control"
placeholder="Notes: "
:class="{
'is-invalid': form.errors.has(
'task_notes'
)
}"
></textarea>
<has-error :form="form" field="task_notes"></has-error>
</div>
<multiple-image-component></multiple-image-component>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button v-show="editmode" type="submit" class="btn btn-success">Update</button>
<button v-show="!editmode" type="submit" class="btn btn-primary">Create New Task</button>
</div>
</div>
</div>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
editmode: true,
tasks: {},
attachments: [],
// formImage: new FormData(),
form: new Form({
id: "",
task_name: "",
task_description: "",
task_assigned_by: "",
task_assigned_to: "",
task_to_be_completed_date: "",
task_priority: "",
task_notes: "",
task_status: "",
task_finished: "",
task_image: "",
}),
};
},
methods: {
updateTask() {
this.$Progress.start();
this.form
.put("api/task/" + this.form.id)
.then(() => {
// successfull
$("#addNew").modal("hide");
Swal.fire("Updated", "Task information updated.", "success");
this.$Progress.finish();
Fire_event.$emit("AfterCreate");
})
.catch(() => {
// Unsuccessfull
this.$Progress.fail();
});
},
editModal(task) {
this.editmode = true;
this.form.reset();
$("#addNew").modal("show");
this.form.fill(task);
},
newModal() {
this.editmode = false;
this.form.reset();
$("#addNew").modal("show");
},
deleteTask(id) {
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!",
}).then((result) => {
// Send request to the server
if (result.value) {
this.form
.delete("api/task/" + id)
.then(() => {
Swal.fire("Deleted!", "Task has been deleted.", "success");
Fire_event.$emit("AfterCreate");
})
.catch(() => {
Swal.fire("Failed", "Something went wrong.", "warning");
});
}
});
},
loadTasks() {
axios.get("api/task").then(({ data }) => (this.tasks = data.data));
},
createTask() {
this.$Progress.start();
this.form
.post("api/task")
.then(() => {
Fire_event.$emit("AfterCreate");
$("#addNew").modal("hide");
toast.fire({
icon: "success",
title: "Task Created successfully",
});
this.$Progress.finish();
this.target.reset();
})
.catch(() => {
this.$Progress.fail();
// toast.fire({
// icon: "error",
// title: "The Task was not created.",
// });
});
},
},
created() {
this.loadTasks();
// setInterval(() => this.loadUsers(), 3000);
Fire_event.$on("AfterCreate", () => {
this.loadTasks();
});
},
mounted() {
console.log("Component mounted.");
},
};
</script>
Task.php (Model)
protected $fillable = [
'task_name', 'task_priority', 'task_assigned_to', 'task_assigned_by', 'task_description', 'task_to_be_completed_date', 'task_status',
'task_notes', 'task_finished', 'image'
];
And finally, the MultipleImageUploadComponent.vue from Dropzone
<template>
<div class="container">
<div class="row justify-content-start">
<div class="">
<div class="card">
<div class="card-header">Task Image</div>
<div class="card-body">
<vue-dropzone
ref="myVueDropzone"
id="dropzone"
:options="dropzoneOptions"
></vue-dropzone>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import vue2Dropzone from "vue2-dropzone";
import "vue2-dropzone/dist/vue2Dropzone.min.css";
export default {
components: {
vueDropzone: vue2Dropzone
},
data: function() {
return {
dropzoneOptions: {
url: "/store-multiple-image",
headers: {
"X-CSRF-TOKEN": document.head.querySelector(
"[name=csrf-token]"
).content
}
}
};
},
mounted() {
console.log("Component mounted.");
}
};
</script>
I am new to combining vue and laravel so if you can help me out, I would sure appreciate it.
Now, Dropzone uses an Ajax request and so does the method I was trying to use to upload the rest of my form. This creates a conflict and out of the box, Dropzone will not allow this functionality.
At least now without a log of configuring. In my case, Dropzone is not a viable option and I have to look for a different option to upload multiple images within my form.
I am using the Croppie script to edit images before uploading to my server.
https://foliotek.github.io/Croppie/
The problem is Croppie encodes the cropped image in a base64 format. I have created a hidden input and attached the base64 string. I need to know how to grab the string so i can decode it and post it with my form.
I have tried so many methods but i am stuck. Any help will be appreciated
Controller
$post = new Post;
$post->post_category_id = $request->post_category_id;
$post->title = $request->title;
$post->body = $request->body;
$post->meta_description = $request->meta_description;
$post->slug = $request->slug;
$post->user_id = auth()->id();
$image = $request->input('featimage'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'image_' . time() . '.' . $image_extension[1]; //generating unique file name;
\Storage::disk('public')->put($imageName,base64_decode($image)
$post->save();
}
View
<form class="form-horizontal" action="{{route('posts.store')}}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<fieldset>
<div class="form-group row"><label class="col-md-2 col-form-label">Title</label>
<div class="col-md-10"><input class="form-control" name="title" type="text"><span class="form-text">Please insert a title <small>eg. Exciting new event coming to London</small>
</span></div>
</div>
</fieldset>
<fieldset class="">
<div class="form-group row"><label class="col-md-2 col-form-label">Category</label>
<div class="col-md-10"><select name="post_category_id" class="custom-select custom-select-sm">
#foreach($postCategories as $postCategory)
<option value="{{ $postCategory->id }}">{{ $postCategory->name }}</option>
#endforeach
</select></div>
</div>
</fieldset>
<fieldset>
<div class="form-group row"><label class="col-md-2 col-form-label">Post Body</label>
<div class="col-md-10">
<textarea type="textarea" class="form-control" rows="10" name="body"></textarea>
</div>
</div>
</fieldset>
<fieldset>
<div class="form-group row"><label class="col-md-2 col-form-label">Meta Description</label>
<div class="col-md-10">
<textarea type="textarea" class="form-control" rows="4" name="meta_description"></textarea>
</div>
</div>
</fieldset>
<fieldset>
<select name="tags[]" multiple="multiple" class="form-control select2-multi">
#foreach($tags as $tag)
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
#endforeach
</select>
</fieldset>
</div>
</div><!-- END card-->
</div>
<div class="col-md-4">
<div class="card card-default">
<div class="card-header">Featured Image</div>
<div class="card-body">
<fieldset>
<figure>
<img src="" class="gambar img-responsive img-thumbnail" id="item-img-output" /></figure>
<input type="hidden" id="featimage" name="featimage">
</fieldset>
<input type="file" class="item-img file center-block" name="upload"/>
</label>
</div>
<div>
</div>
<!-- START card-->
<div class="card card-default">
<div class="card-header">Slug</div>
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend"><span class="input-group-text" id="basic-addon1">www.sixmedia.co.uk/</span></div><input class="form-control" name="slug" type="text" placeholder="slug" aria-label="Username" aria-describedby="basic-addon1">
</div>
</div>
</div><!-- END card-->
<!-- START card-->
<div class="card card-default">
<div class="card-header">Featured</div>
<div class="card-body">
<div class="col-md-12">
<fieldset>
<div class="form-group row">
#foreach($featured as $feat)
<div class="checkbox c-checkbox"><label><input name="featured[]" type="checkbox" value="{{$feat->id}}"><span class="fa fa-check"></span>{{ $feat->name }} </label></div>
#endforeach
</div>
</fieldset>
</div>
</div>
</div><!-- END card-->
<button class="btn btn-primary btn-block" name="submit">Save</button>
<button class="btn btn-danger btn-block" name="submit">Cancel</button>
</form>
JS
<script type="text/javascript">
$(".gambar").attr("src", "http://www.pngall.com/wp-content/uploads/2/Upload-PNG-Image-File.png");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 500,
height: 281,
},
enforceBoundary: false,
enableExif: true
});
$('#cropImagePop').on('shown.bs.modal', function(){
// alert('Shown pop');
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
console.log('jQuery bind complete');
});
});
$('.item-img').on('change', function () { imageId = $(this).data('id'); tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId); readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'base64',
format: 'png',
size: {width: 350, height: 200}
}).then(function (resp) {
$('#item-img-output').attr('src', resp);
$('#featimage').attr('src', resp);
$('#cropImagePop').modal('hide');
});
});
// End upload preview image
</script>
The problem seems to be in your jquery script, you are setting the base64 string as the source of <input type="hidden" id="featimage">
change this:
$('#featimage').attr('src', resp);
to this
`$('#featimage').val(resp);`
This question already has answers here:
Stop form refreshing page on submit
(20 answers)
How can I prevent refresh of page when button inside form is clicked?
(16 answers)
Closed 4 years ago.
Im trying to insert data with ajax, but i got error :
Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException
This is my form in add-gallery.blade.php:
<form method="post" action="" enctype="multipart/form-data" autocomplete="off" class="mt-4 mb-4 card p-4">
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="gallery_name">Name</label>
</div>
<div class="col-md-6 align-self-center">
<input type="text" name="gallery_name" id="gallery_name" class="form-control" placeholder="Type Gallery Name" />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="category">Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="category" id="category">
<option value="">Select Category</option>
<option value="Home">Home</option>
<option value="Office">Office</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="subcategory">Sub Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="subcategory" id="subcategory">
<option value="">Select Sub Category</option>
<option value="Interior">Interior</option>
<option value="Eksterior">Eksterior</option>
<option value="Decoration">Decoration</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="subsubcategory">Subsub Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="subsubcategory" id="subsubcategory">
<option value="">Select Subsub Category</option>
<option value="Room">Room</option>
<option value="Bathroom">Bathroom</option>
<option value="Kitchen">Kitchen</option>
<option value="Terrace">Terrace</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label for="gallery_image">Image</label>
</div>
<div class="col-md-10">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail w-100" style="display: none;">
<img src="http://placehold.it/1186x800" />
</div>
<div id="toAnnotate" class="fileinput-preview fileinput-exists thumbnail w-100"></div>
<div>
<span class="btn btn-xs btn-success btn-file"><span class="fileinput-new">Select image</span><span class="fileinput-exists">Change</span><input type="file" name="gallery_image" id="gallery_image"></span>
Remove
</div>
</div>
<p><small><em>Image Size : 1186px (width), 800px (height)</em></small></p>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center"> </div>
<div class="col-md-10 align-self-center">
<button type="button" class="btn btn-secondary">Cancel</button>
<button type="submit" class="btn btn-success" id="save">Save</button>
</div>
</div>
</div>
</form>
And below is my ajax in same page add-gallery.blade.php:
<script type="text/javascript">
$(document).ready(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Save
$('#save').on('click', function () {
var gallery_name = $('#gallery_name').val();
var category = $('#category').val();
var subcategory = $('#subcategory').val();
var subsubcategory = $('#subsubcategory').val();
var gallery_image = $('#gallery_image').val();
var dataSubmit = $(this).serialize();
var top = top;
var left = left;
var file_data = $('#gallery_image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : "{{ url('galleries/store') }}",
dataType : 'text', // what to expect back from the server
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
dataType : 'json',
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
});
</script>
This is my routes file web.php:
Route::post('galleries/store','Dashboard\GalleryController#store');
And this is my controller GalleryController.php:
public function store(Request $request){
if($request->hasFile('gallery_image')){
$fileImage = $request->file('gallery_image');
$fileImageExtension = $fileImage->extension();
$renameFileImage = 'ImageGalleries'.time().'.'.$fileImageExtension;
$pathFileImage = $fileImage->storeAs('public/galleries_documents/images_galleries', $renameFileImage); /images_articles
$galleries = new Gallery;
$points = new Point;
$galleries->name = $request->gallery_name;
$galleries->category = $request->category;
$galleries->sub_category = $request->subcategory;
$galleries->sub_subcategory = $request->subsubcategory;
$galleries->image = $renameFileImage;
$galleries->lang_id = session('lang_id');
$galleries->save();
$lastInsertId = $galleries->id;
for($i = 0; $i < count($request->node); $i++) {
$node[] = [
'node_position_top' => $request->node[$i],
'node_position_left' => $request->node[$i],
'id_gallery' => $lastInsertId,
];
$points->lang_id = session('lang_id');
}
Point::insert($node); //save to table
print_r($node[]);
exit();
}
}