My problem occur in a specific case,
I'm using laravel 7, trying to make small contacts list datatable using ajax CRUD operations .
On localhost every thing is OK but when I deploy it to local network I get (404 not found ajax response)
may controller code:
public function index(Request $request)
{
$cities = State::where("country_id",223 )->get();//223 turkey
$countries = [];
$countries = Country::all(); //select('name')->get()
$datasources = [];
$datasources = DB::table('contacts')->select('data_source')->distinct()->get()->toArray();
$contact_types = [];
$contact_types = DB::table('contacts')->select('contact_type')->distinct()->get()->toArray();
$data = DB::table("contacts")
->leftjoin("countries","contacts.country","=","countries.id")
->leftjoin("states","contacts.city","=","states.id")
->select("contacts.*", "countries.name as countryname", "states.name as statename")
->latest()->get();
if ($request->ajax()) {
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'edit';
$btn = $btn.' delete';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('contacts.contactAjax')->with([ 'contacts'=>$data,
'countries'=> $countries,
'cities'=> $cities,
'datasources'=> $datasources,
'contact_types'=> $contact_types]); //,compact('contacts'));
}
and here may whole view code:
#extends('contacts.layout')
#section('content')
<div class="container">
<h1>Arabist CRM </h1>
<a class="btn btn-success" href="javascript:void(0)" id="createNewContact"> Add contact</a>
<button id="btn-export">EXCEL</button>
{{--onclick="exportTableToExcel('tbl_contacts','conts.xlsx')" <a class="btn btn-success" href="javascript:exportTableToExcel('tbl_contacts','contacts.xlsx')" id="xlsx-export"> excel</a> --}}
<table class="table table-bordered data-table" id="tbl_contacts">
<thead>
<tr>
<th style="padding:10pt 20pt 2pt 2pt; background-image:none;" width="20pt">No</th>
<th style="min-width:75pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="10%">name</th>
<th style="min-width:50pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="10%">company</th>
{{-- <th width="10%">birth</th>
<th>الجنس</th> --}}
<th style="min-width:75pt; padding:10pt 20pt 2pt 2pt; background-image:none;" >email</th>
<th style="min-width:50pt; padding:10pt 20pt 2pt 2pt; background-image:none;">phone</th>
<th style="min-width:120pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="15%">notes</th>
<th style="min-width:40pt; padding:10pt 20pt 2pt 2pt; background-image:none;">contact type</th>
<th style="min-width:40pt; padding:10pt 20pt 2pt 2pt; background-image:none;">city</th>
<th style="min-width:65pt; padding:10pt 20pt 2pt 2pt; background-image:none;">address</th>
<th style="min-width:80pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="8%" style="min-width:100px">control</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal fade" id="ajaxModel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
</div>
<div class="modal-body">
<form id="contactForm" name="contactForm" class="form-horizontal">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">company</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="company_name" name="company_name" placeholder="Enter Name" value="" maxlength="50" >
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">email</label>
<div class="col-sm-12">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Name" value="" >
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-2 control-label">phone</label>
<div class="col-sm-12">
<input type="tel" class="form-control" id="phone" name="phone" placeholder="Enter Name" value="" maxlength="50" required="required">
</div>
</div>
<div class="form-group">
<label for="contact_type" class="col-sm-2 control-label">type</label>
<div class="col-sm-12">
<input class="form-control" type="text" list="contact_types" name="contact_type" id="contact_type" placeholder="type" />
<datalist name = "contact_types" id = "contact_types" >
#foreach ($contact_types as $ctp)
<option >{{ $ctp->contact_type }}</option>
#endforeach
</datalist>
</div>
</div>
<div class="form-group" style="display:none;">
<label for="country" class="col-sm-2 control-label" >country</label>
<div class="col-sm-12">
<select class="form-control input-sm" name="country" id="country">
<option value="">--select--</option>
#foreach ($countries as $cnt)
#if($cnt->id == 223 )
<option value="{{ $cnt->id }}" selected>{{$cnt->name}}</option>
#else
<option value="{{ $cnt->id }}">{{$cnt->name}}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="form-group" style="display:none;">
<label for="city" class="col-sm-2 control-label">city</label>
<div class="col-sm-12">
<select class="form-control input-sm" name="city" id="city">
<option value="">--select--</option>
#foreach ($cities as $cnt)
#if($cnt->id == 3703 )
<option value="{{ $cnt->id }}" selected>{{$cnt->name}}</option>
#else
<option value="{{ $cnt->id }}">{{$cnt->name}}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">address</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="address" name="address" placeholder="Enter address" maxlength="50" >
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">notes</label>
<div class="col-sm-12">
<textarea id="notes" name="notes" required="" placeholder="Enter Details" class="form-control"></textarea>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
more details
<button type="submit" class="btn btn-primary" id="saveBtn" value="create">save
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function exportTableToExcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
var table = $('#tbl_contacts').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('ajaxcontacts.index') }}",// "{{ route('ajaxcontacts.index') }}",{{ url('ajaxcontacts.index')}}
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'company_name', name: 'company_name'},
{data: 'email', name: 'email'},
{data: 'phone', name: 'phone'},
{data: 'notes', name: 'notes'},
{data: 'contact_type', name: 'contact_type'},
{data: 'statename', name: 'city'},
{data: 'address', name: 'address'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$('#btn-export').click(function () {
exportTableToExcel("tbl_contacts","fuc.xlsx");
});
$('#createNewContact').click(function () {
$('#saveBtn').val("create-contact");
$('#id').val('');
$('#contactForm').trigger("reset");
$('#modelHeading').html("Create New Contact");
$('#ajaxModel').modal('show');
});
$('body').on('click', '#moreDetails', function () {
var id = $('#id').val();
alert("id: "+ id);
window.location.href = "contacts" +'/' + id +'/edit';//"{{ route('contacts.index') }}"
//$.get("{{ route('contacts.index') }}" +'/' + id +'/edit')
});
$('body').on('click', '.editContact', function () {
var id = $(this).data('id');
//alert("id: "+ id);
$.get( "{{ route('ajaxcontacts.index') }}" + "/" + id +"/edit", function (data) {
//alert("data.name: " + data.name)
$('#modelHeading').html("Edit Contact");
$('#saveBtn').val("edit-user");
$('#ajaxModel').modal('show');
$('#id').val(data.id);
$('#name').val(data.name);
$('#company_name').val(data.company_name);
$('#email').val(data.email);
$('#phone').val(data.phone);
$('#notes').val(data.notes);
$('#contact_type').val(data.contact_type);
$('#data_source').val(data.data_source);
$('#country').val(data.country);
$('#city').val(data.city);
$('#address').val(data.address);
})
});
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#contactForm').serialize(),
url: "{{ route('ajaxcontacts.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#contactForm').trigger("reset");
$('#ajaxModel').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('save changes');
}
});
});
$('body').on('click', '.deleteContact', function () {
var id = $(this).data("id");
confirm("Are You sure want to delete !");
$.ajax({
type: "DELETE",
url: "{{ route('ajaxcontacts.store') }}"+'/'+id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
</body>
#endsection
and web.php routes
Route::resource('ajaxcontacts','ContactAjaxController')->Middleware('isAdmin');
Route::get('ajaxcontacts/index', 'ContactAjaxController#index');
The issue is that you are calling a route from your ajax code, but you have not set up a named route within your web.php route file.
When you use the route() method, Laravel looks for a named route. You call this method several times in your blade file here:
"{{ route('ajaxcontacts.index') }}"
To Fix just name the route in your web.php file:
Route::get('ajaxcontacts/index', 'ContactAjaxController#index')->name('ajaxcontacts.index');
Related
Hi every one, I am using laravel 8, and i want to update data using model, now i am facing little problem. The Problem is only details are update but file or image did not updated, i give every thing in bellow,
Blade Code: THis is my datatable
<table class="table display" width="100%" id="example">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Image</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#php
$i=0;
#endphp
#foreach ($banner as $item )
<tr id="banner-{{ $item->id }}">
<td>{{ ++$i }}</td>
<td>{{ $item->title }}</td>
<td><img src="{{ asset('/assets/image/banner/'.$item->image) }}" alt="" style="width: 100px; height:100px"></td>
<td><input type="checkbox" name="status" class="status" id="status" data-toggle="toggle" data-on="Active" data-off="Deactive" data-onstyle="success" data-offstyle="danger" data-id="{{ $item->id }}" {{ $item->status == 'Active' ? 'checked' : '' }}></td>
<td>
<a class="btn btn-outline-warning btn-sm" href="javascript:void(0);" onclick="editbanner({{ $item->id }})"><i class="fas fa-pencil-alt"></i></a>
<i class="mdi mdi-trash-can"></i>
</td>
</tr>
#endforeach
</tbody>
</table>
Update Model here is data update model, that i create for update data.
<div class="modal fade" id="BannerEditModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<div class="text-center">
<h3 class="modal-title" id="exampleModalLabel">Insert Position & Salary</h3>
</div>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul id="BannerForm_errorlist"></ul>
<form class="forms-sample" id="bannereditform" method="post">
#csrf
<input type="hidden" name="id" id="id">
<div class="form-group">
<label>Title<small class="text-danger">*</small></label>
<input type="text" id="title1" name="title1" class="form-control" />
</div>
<div class="form-group">
<label>Banner Image<small class="text-danger">*</small></label>
<input type="file" id="image1" name="image1" class="form-control" />
</div>
<div class="text-center pb-2">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success submit" name="submit" id="submit" value="Update" />
</div>
</form>
</div>
</div>
</div>
Ajax Part This is Ajax code for data fetching and data uploading
function editbanner(id) {
$.get("/banner/edit/" + id, function(banner) {
$('#id').val(banner.id);
$('#title1').val(banner.title);
$('#BannerEditModal').modal("toggle");
});
}
$('#bannereditform').submit(function(e) {
e.preventDefault();
let id = $('#id').val();
var title1 = $('#title1').val();
var image1 = $('#image1').val();
let _token = $('input[name=_token]').val();
console.log(image1);
$.ajax({
type: "PUT"
, url: "/banner/update"
, data: {
id: id
, title1: title1
, image1: image1
, _token: _token
, }
, dataType: "json"
, success: function(response) {
// console.log(response);
$('#banner' + response.id + 'td:nth-child(1)').text(response.title1);
$('#banner' + response.id + 'td:nth-child(2)').val(response.image1);
$('#BannerEditModal').modal("toggle");
// location.reload();
$('#bannereditform')[0].reset();
}
});
});
Controller
public function update(Request $request)
{
$banner = Banner::find($request->id);
$banner->title = $request->input('title1');
if($request->hasFile('image1')){
$destination = public_path().'/assets/image/banner/'.$banner->image;
if(File::exists($destination)){
File::delete($destination);
}
$image = $request->file('image1');
$image_name = time().'.'.$image->getClientOriginalExtension();
$image->move(public_path().'/assets/image/banner/',$image_name);
$banner->image = $image_name;
}
$banner->save();
return response()->json($banner);
}
Route Here is my data fatching and data updating route
Route::get('/banner/edit/{id}', "App\Http\Controllers\BannerController#edit")->name('banner.edit');
Route::put('/banner/update', "App\Http\Controllers\BannerController#update")->name('banner.update');
you need to change the way you getting value from #image from
var image1 = $('#image1').val();
to
var image1 = $('#image1').prop('files')[0]
You are missing enctype in your modal form:
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
Note: The enctype attribute can be used only if method="post".
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<div class="text-center">
<h3 class="modal-title" id="exampleModalLabel">Insert Position & Salary</h3>
</div>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul id="BannerForm_errorlist"></ul>
<form class="forms-sample" id="bannereditform" method="post" enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" id="id">
<div class="form-group">
<label>Title<small class="text-danger">*</small></label>
<input type="text" id="title1" name="title1" class="form-control" />
</div>
<div class="form-group">
<label>Banner Image<small class="text-danger">*</small></label>
<input type="file" id="image1" name="image1" class="form-control" />
</div>
<div class="text-center pb-2">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success submit" name="submit" id="submit" value="Update" />
</div>
</form>
</div>
</div>
Ajax : to send form files and data to Back-end we are using Form Data objects:
$('#bannereditform').submit(function(e) {
e.preventDefault();
let formData = new FormData($('#bannereditform')[0]);
$.ajax({
type: "PUT"
, url: "/banner/update"
, data:formData,
, dataType: "json",
processData: false
, success: function(response) {
// console.log(response);
$('#banner' + response.id + 'td:nth-child(1)').text(response.title1);
$('#banner' + response.id + 'td:nth-child(2)').val(response.image1);
$('#BannerEditModal').modal("toggle");
// location.reload();
$('#bannereditform')[0].reset();
}
});})
When you save, other input data comes to the database, while the data from TourDay does not come. The relationship is established in the Migration and Model section. I could not do it in the controller part, how can I do something..
my blade:
<div class="row">
<div class="col-lg-12">
<div class="card card-custom card-stretch ">
<div class="card-header">
<h3 class="card-title">GRUP OLUŞTUR</h3>
</div>
<form method="post" class="form" id="dynamic_form" enctype="multipart/form-data">
#csrf
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li><b>{{ $error }}</b></li>
#endforeach
</ul>
</div>
#endif
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Otel Seçimi:</strong></label>
<div class="col-lg-3">
<select class="form-control select2 " id="kt_select2_5" name="hotel[]" multiple="" tabindex="-1" aria-hidden="true">
<optgroup label="Oteller">
#foreach($hotels as $hotel)
<option value="{{$hotel->id}}" >{{$hotel->name}}</option>
#endforeach
</optgroup>
</select>
</div>
<label class="col-lg-2 col-form-label text-lg-right"><strong>Grup Kodu :</strong></label>
<div class="col-lg-3">
<div class="input-group input-group">
<div class="input-group-prepend"><span class="input-group-text" >Grup-Kodu:</span></div>
<input type="text" class="form-control form-control-solid" placeholder="TourKey-123-456" name="code" value="{{old('code')}}">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Rehber Ata:</strong></label>
<div class="col-lg-3">
<select class="form-control form-control-solid" id="exampleSelectd" name="guide_id">
#foreach($guides as $guide)
<option value="{{ $guide->id }}" #if(old('guide_id')===$guide->id) selected #endif>{{$guide->full_name}}</option>
#endforeach
</select>
</div>
<label class="col-lg-2 col-form-label text-lg-right"><strong>Müşteri Seçimi:</strong></label>
<div class="col-lg-3">
<select class="form-control select2 " id="kt_select2_3" name="user[]" multiple="" data-select2-id="kt_select2_3" tabindex="-1" aria-hidden="true">
<optgroup label="Müşteriler" >
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->full_name}}</option>
#endforeach
</optgroup>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Başlangıç Tarihi:</strong></label>
<div class="col-lg-3">
<div class="input-group date">
<input type="text" class="form-control" id="kt_datepicker_2" name="started_at" value="{{old('started_at')}}" placeholder="Başlangıç Tarihi seçin.">
<div class="input-group-append">
<span class="input-group-text">
<i class="la la-calendar-check-o"></i>
</span>
</div>
</div>
</div>
<label class="col-lg-2 col-form-label text-lg-right"><strong>Bitiş Tarihi:</strong></label>
<div class="col-lg-3">
<div class="input-group date">
<input type="text" class="form-control" id="kt_datepicker_2" name="finished_at" value="{{old('finished_at')}}" placeholder="Başlangıç Tarihi seçin.">
<div class="input-group-append">
<span class="input-group-text">
<i class="la la-calendar-check-o"></i>
</span>
</div>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label text-lg-right"><strong>Aktivite olacak mı? (Opsiyonel)</strong></label>
<div class="col-lg-3 d-flex justify-content-center">
<div class="radio-inline">
<label class="radio radio-lg">
<input type="radio" onclick="aktivite(0)" #if(old('activity')) checked="checked" #endif name="radios3_1" class="form-control"/>
<span></span>
Evet
</label>
<label class="radio radio-lg">
<input type="radio" onclick="aktivite(1)" #if(!old('activity')) style='display:none' #endif name="radios3_1" class="form-control"/>
<span></span>
Hayır
</label>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right" for="kt_select2_2"></label>
<div class="col-lg-4">
<div class="form-group" id="myAktivite">
<label for="kt_select2_2"><strong>Aktivite Seçimi Yapın:</strong></label>
<select class="form-control select2 " id="kt_select2_2" name="activity[]" multiple="" data-select2-id="kt_select2_2" tabindex="-1" aria-hidden="true">
<optgroup label="Aktiviteler">
#foreach($activities as $activity)
<option value="{{$activity->id}}">{{$activity->title}}</option>
#endforeach
</optgroup>
</select>
</div>
</div>
</div>
</div>
<div class="separator separator-dashed my-8"></div>
<div class="row col-lg-6">
<div class="col-lg-1"></div>
<h4 class="title col-lg-4">TUR EKLE</h4>
</div>
<div class="separator separator-dashed my-8"></div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right"><strong>Tur Başlığı:</strong></label>
<div class="col-lg-3">
<input type="text" name="tour_title" value="{{old('tour_title')}}" class="form-control form-control-solid" placeholder="Lütfen tur başlığı giriniz"/>
</div>
<label class="col-lg-2 col-form-label text-lg-right"></label>
<div class="col-lg-3">
<div class="custom-file form-group">
<input type="file" class="custom-file-input form-control-solid" id="customFile" multiple>
<label class="custom-file-label" for="customFile">Resim Yükle</label>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 col-form-label text-lg-right" for="editable"><strong>İçerik Detay</strong></label>
<div class="col-lg-8">
<textarea id="editable" class="form-control" placeholder="" name="tour_description" value="{{old('tour_description')}}">
</textarea>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-8">
<h3 align="center">Tur Detayı (Gün gün yapılacakları ekleyin):</h3>
<br />
<div class="table-responsive">
<span id="result"></span>
<table class="table table-bordered table-striped" id="user_table">
<thead>
<tr>
<th width="22%">Başlık(Kaçıncı Gün)</th>
<th width="22%">İçerik</th>
<th width="22%">Öğle Yemeği</th>
<th width="22%">Akşam Yemeği</th>
<th width="12%">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div class="card-footer">
<div class="row ">
<div class="col-lg-10 d-flex justify-content-end">
<button type="submit" name="save" id="save" class="btn btn-success mr-2">Kaydet</button>
<button type="reset" class="btn btn-secondary">İptal Et</button>
</div>
<div class="col-lg-2"></div>
</div>
</div>
</form>
</div>
</div>
my script:
<script>
$(document).ready(function(){
var count = 1;
dynamic_field(count);
function dynamic_field(number)
{
html = '<tr>';
html += '<td><input type="text" name="title[]" class="form-control" /></td>';
html += '<td><input type="text" name="description[]" class="form-control" /></td>';
html += '<td><input type="text" name="lunch[]" class="form-control" /></td>';
html += '<td><input type="text" name="dinner[]" class="form-control" /></td>';
if(number > 1)
{
html += '<td><button type="button" name="remove" id="" class="btn btn-light-danger remove"><i class="la la-trash-o">Sil</button></td></tr>';
$('tbody').append(html);
}
else
{
html += '<td><button type="button" name="add" id="add" class="btn btn-light-success"><i class="la la-plus"> Ekle' +
'' +
'</button></td></tr>';
$('tbody').html(html);
}
}
$(document).on('click', '#add', function(){
count++;
dynamic_field(count);
});
$(document).on('click', '.remove', function(){
count--;
$(this).closest("tr").remove();
});
$('#dynamic_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:'{{ route("groups.store") }}',
method:'post',
data:$(this).serialize(),
dataType:'json',
beforeSend:function(){
$('#save').attr('disabled','disabled');
},
success:function(data)
{
if(data.error)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<p>'+data.error[count]+'</p>';
}
$('#result').html('<div class="alert alert-danger">'+error_html+'</div>');
}
else
{
dynamic_field(1);
$('#result').html('<div class="alert alert-success">'+data.success+'</div>');
}
$('#save').attr('disabled', false);
}
})
});
});
</script>
my Group Model:
protected $fillable = [
'guide_id','code','started_at','finished_at','tour_title','tour_description'
];
public function tourDays(){
return $this ->hasMany('App\Models\TourDay');
}
my TourDay Model:
protected $fillable = [
'group_id','title', 'description','lunch','dinner'
];
public function group(){
return $this ->belongsTo('App\Models\Group');
}
my GroupController:
public function store(Request $request)
{
$data=$request->only('guide_id','code','started_at','finished_at','tour_title','tour_description');
$group=Group::create($data);
if($request->ajax())
{
$rules = array(
'title.*' => 'required',
'description.*' => 'required',
'lunch.*'=>'required',
'dinner.*'=>'required',
);
$error =Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json([
'error' => $error->errors()->all()
]);
}
$title = $request->title;
$description = $request->description;
$lunch = $request->lunch;
$dinner = $request->dinner;
for($count = 0; $count < count($title); $count++)
{
$tourDay = new TourDay([
'title' => $title[$count],
'description' => $description[$count],
'lunch' => $lunch[$count],
'dinner' => $dinner[$count]]);
$group->tourDays()->saveMany($tourDay);
$data = array(
'title' => $title[$count],
'description' => $description[$count],
'lunch' => $lunch[$count],
'dinner' => $dinner[$count]
);
$insert_data[] = $data;
}
TourDay::insert($insert_data);
}
return redirect()
->route('groups.index')->withMessage('Rehber başarıyla oluşturuldu!');
}
In your store method put this codes:
public function store(Request $request) {
$data=$request->only('guide_id', 'code', 'started_at', 'finished_at','tour_title', 'tour_description');
$group=Group::create($data);
if($request->ajax())
{
$rules = array(
'title.*' => 'required',
'description.*' => 'required',
'lunch.*'=>'required',
'dinner.*'=>'required',
);
$error =Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json([
'error' => $error->errors()->all()
]);
}
$title = $request->title;
$description = $request->description;
$lunch = $request->lunch;
$dinner = $request->dinner;
for($count = 0; $count < count($title); $count++)
{
$tourDay = [
'title' => $title[$count],
'description' => $description[$count],
'lunch' => $lunch[$count],
'dinner' => $dinner[$count],
'group_id' => $group->id
];
TourDay::create($tourDay);
}
}
return redirect()
->route('groups.index')->withMessage('Rehber başarıyla oluşturuldu!');
}
I use Laravel and Vue. I have two components: parent and child.
Parent:
<template>
<div>
<sport-sites-add :applications-all-list="applicationsAll"></sport-sites-add>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Application id</th>
<th scope="col">Name</th>
<th scope="col">Description</th>
<th scope="col">Picture</th>
<th scope="col">URL</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="sportSite in sportSites">
<th scope="row">{{ sportSite.id }}</th>
<td>
<template v-for="application in sportSite.applications">
id {{ application.id }} => {{ application.name }} <br>
</template>
</td>
<td>{{ sportSite.name }}</td>
<td>{{ sportSite.description }}</td>
<td>
<img style="width: 100px; height: 100px;" :src="sportSite.image" >
</td>
<td>
<a :href="sportSite.url" target="_blank">{{ sportSite.url }}</a>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { EventBus } from '../../app';
export default {
name: "SportSitesTable",
mounted(){
this.loadTable();
this.getApplications();
},
methods:{
loadTable: function () {
window.axios.get('/sport_sites_all')
.then(resp => {
this.sportSites = resp.data.data;
}).catch(err => {
console.error(err);
});
},
getApplications: function () {
window.axios.get('/applications/all')
.then(resp => {
this.applicationsAll = resp.data.applications.data;
}).catch(err => {
console.error(err);
});
}
},
data(){
return {
sportSites: [],
applicationsAll: [],
}
},
}
</script>
Child:
<template>
<div>
<button type="button" class="btn btn-primary my-2" data-toggle="modal" data-target="#sportSiteAdd">
Add
</button>
<div class="modal fade" id="sportSiteAdd" tabindex="-1" role="dialog" aria-labelledby="sportSiteAddLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="sportSiteAddLabel">Add sport site</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul class="alert-danger">
<li v-for="error in errors">
{{ error[0] }}
</li>
</ul>
<form>
<div class="form-group">
<label for="name">Title</label>
<input type="text" class="form-control" id="name" name="name" v-model="formFields.name">
</div>
<div class="form-group">
<label for="image">Picture</label>
<input type="text" class="form-control" id="image" name="image" v-model="formFields.image">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="text" class="form-control" id="url" name="url" v-model="formFields.url">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" v-model="formFields.description"></textarea>
</div>
<div>
<label class="typo__label">Applications </label>
<multiselect v-model="formFields.applications"
tag-placeholder="Applications"
placeholder="Search"
label="name"
track-by="id"
:options="applications"
:multiple="true"
:taggable="true">
</multiselect>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" v-on:click="submit">Save</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { EventBus } from '../../app';
import Multiselect from 'vue-multiselect'
export default {
name: "SportSitesAdd",
props: ['applicationsAllList'],
methods:{
submit: function (e) {
window.axios.post('/sport_site/add/', this.formFields)
.then(res => {
console.log('Saved!');
$('#sportSiteAdd').modal('hide');
this.formFields.name = '';
this.formFields.image = '';
this.formFields.url = '';
this.formFields.description = '';
EventBus.$emit('reloadApplicationsTable');
}).catch(err => {
if(err.response.status === 422){
this.errors = err.response.data.errors || [];
}
console.error('Error of saving!');
});
},
},
data(){
return {
formFields: {
name: '',
image: '',
url: '',
description: '',
applications: this.applicationsAllList,
},
errors: [],
}
},
components: {
Multiselect
},
}
</script>
The parent component is a table. Child component is a form for the table. I pass a data from the parent to the child via props:
<sport-sites-add :applications-all-list="applicationsAll"></sport-sites-add>
In the child component I have a plugin for creating a multiple select. The plugin requires 'options' and 'values' collections. It's very simple, documentation with my case is here https://vue-multiselect.js.org/#sub-tagging. At the result I want to see the following: all items on the select are selected. But I have just the empty collection during mounting of the child component. I have available items on the 'select' but I dont know how I can make it selected by default. Obviously, I need to copy the applicationsAllList into local data() of child component and use it. But it not available during mounted and beforeMounted.
console.log tells me that the child is faster.
you're missing #tag function & v-model, in this case, must be array, You need to use applicationsAllList props directly on options
<multiselect v-model="formFields.value"
tag-placeholder="Applications"
placeholder="Search"
label="name"
track-by="id"
:options="applicationsAllList"
:multiple="true"
#tag="addTag"
:taggable="true">
</multiselect>
in methods add addTag function and add value as array
data() {
return {
formFields: {
name: '',
value: [],
image: '',
url: '',
description: '',
},
errors: [],
}
},
methods: {
addTag (newTag) {
const tag = {
name: newTag,
code: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
}
this.options.push(tag)
this.value.push(tag)
}
}
I'm trying to update some data in Model using API in Laravel and Vue.js
but I can't do this because axios doesn't send any data to server, I'm checking the data right before sending and they exist (I use FormData.append to add all fields)
I check data before sending using the code:
for(var pair of formData.entries()) {
console.log(pair[0]+ ': '+ pair[1]);
}
and I get this result:
You can check the appropriate code:
[function for updating]
updateStartup() {
let formData = new FormData();
formData.append('startup_logo', this.update_startup.startup_logo);
formData.append('country_id', this.update_startup.country_id);
formData.append('category_id', this.update_startup.category_id);
formData.append('startup_name', this.update_startup.startup_name);
formData.append('startup_url', this.update_startup.startup_url);
formData.append('startup_bg_color', this.update_startup.startup_bg_color);
formData.append('startup_description', this.update_startup.startup_description);
formData.append('startup_public', this.update_startup.startup_public);
axios.put('/api/startup/' + this.update_startup.id, formData, { headers: {
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error.response);
});
}
[controller method where I should receive data]:
public function update(Request $request, $id) {
return $request; // just for checking if I get data
...
}
[HTML with vue.js where I use object which I send in updateStartup function]:
<!-- Modal edit -->
<div class="modal fade editStartUp" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<img src="/admin/images/modal-cross.png" alt="Close">
</button>
</div>
<div class="modal-body">
<form method="POST" enctype="multipart/form-data" #submit.prevent="updateStartup">
<h4 class="sel-c-t">Select category</h4>
<div class="submit-fields-wr">
<select name="category" v-model="update_startup.category_id" class="selectpicker select-small" data-live-search="true" #change="updateCategoryDetails()">
<option v-for="category in categories" :value="category.id" :selected="category.id == update_startup.category_id ? 'selected' : ''" >{{ category.name }}</option>
</select>
<select v-if="update_startup.is_admin" name="country" v-model="update_startup.country_id" class="selectpicker select-small" data-live-search="true" #change="updateCountryDetails()">
<option v-for="country in countries" :value="country.id" :selected="country.id == update_startup.country_id ? 'selected' : '' ">{{country.name }}</option>
</select>
</div>
<div class="submit-fields-wr">
<input type="text" placeholder="Startup name" v-model="update_startup.startup_name">
<input type="url" v-model="update_startup.startup_url" placeholder="URL">
</div>
<textarea v-model="update_startup.startup_description" name="startup_description" placeholder="Describe your startup in a sentence.">
</textarea>
<div v-if="!update_startup.is_admin">
<h4 class="sel-c-t bold">Contact details:</h4>
<div class="submit-fields-wr">
<select name="country" v-model="update_startup.country_id" class="selectpicker select-small" data-live-search="true" #change="updateCountryDetails()">
<option v-for="country in countries" :value="country.id" :selected="country.id == update_startup.country_id ? 'selected' : '' ">{{country.name }}</option>
</select>
<input type="text" placeholder="Your Name" v-model="update_startup.contact_name">
</div>
<div class="submit-fields-wr">
<input type="text" v-model="update_startup.contact_phone" placeholder="Your phone number">
<input type="email" v-model="update_startup.contact_email" placeholder="Your email address">
</div>
</div>
<p class="upl-txt">Company’s logo.<span>(upload as a png file, less than 3mb)</span></p>
<div class="file-upload">
<div class="logo-preview-wr">
<div class="img-logo-preview">
<img :src="update_startup.startup_logo" alt="logo preview" id="img_preview">
</div>
</div>
<label for="upload" class="file-upload_label">Browse</label>
<input id="upload" #change="onFileUpdated" class="file-upload_input" type="file" name="file-upload">
</div>
<div class="preview-divider"></div>
<h4 class="sel-c-t bold">Preview:</h4>
<div class="preview-wrapper-row">
<a href="#" class="start-up-wr">
<div class="start-up-part-1 edit">
<div class="flag-cat-wr">
<div class="flag-wr">
<img :src="update_startup.country_flag" :alt="update_startup.country_name">
</div>
<div class="category-wr">
{{ update_startup.category_name }}
</div>
</div>
<img :src="update_startup.startup_logo" :alt="update_startup.startup_name" class="start-up-logo">
</div>
<div class="start-up-part-2">
<h4 class="startup-name">{{ update_startup.startup_name }}</h4>
<p class="startup-description">
{{ update_startup.startup_description }}
</p>
</div>
</a>
<div class="color-picker-btns-wr">
<div>
<input type="text" class="color_picker" v-model="update_startup.startup_bg_color">
<button class="colo_picker_btn">Background Color</button>
</div>
<div class="modal-bottom-btns">
<div class="btn-deactivate-active">
<button type="submit" class="btn-deactivate" #click="deactivateExistingStartup()">Deactivate</button>
<button type="submit" class="btn-activate" #click="activateExistingStartup()">Activate</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Modal edit -->
[Additional info - also when I open modal(where I have form for updating) I change form data accordingly to startup id]:
showUpdateStartup(startup) {
setTimeout(() => {
$('.selectpicker').selectpicker('refresh');
}, 50);
this.update_startup.id = startup.id;
this.update_startup.category_id = startup.category.id;
this.update_startup.category_name = startup.category.name;
this.update_startup.startup_name = startup.name;
this.update_startup.startup_description = startup.description;
this.update_startup.startup_url = startup.url;
this.update_startup.startup_logo = startup.logo;
this.update_startup.startup_bg_color = startup.startup_bg_color;
this.update_startup.contact_id = startup.contact.id;
this.update_startup.contact_name = startup.contact.name;
this.update_startup.contact_phone = startup.contact.phone;
this.update_startup.contact_email = startup.contact.email;
this.update_startup.country_id = startup.contact.country.id;
this.update_startup.country_flag = startup.contact.country.flag;
this.update_startup.country_name = startup.contact.country.name;
this.update_startup.is_admin = startup.contact.is_admin;
this.update_startup.startup_public = startup.public;
},
Let me know if you have any additional questions
Thank you guys a lot for any help and ideas!
Try using formData.append('_method', 'PATCH') with axios.post method.
Return the input data instead of the Request object from your controller:
return $request->input();
i have created a form for editing the record from db there is different time slots and i want to make delete function for them so i made a ajax call but am confused in URL www.hostname.com/dental/public/admin/manageschedule/1/api/ajax 404 (Not Found)
how to call ajax inside a laravel edit form
here is what i have done:
#extends('admin.layouts.app_inner')
#section('htmlheader_title')
Home
#endsection
#section('content')
#if (count($errors))
#foreach($errors->all() as $error)
<div class="alert alert-danger"><i class="fa fa-fw fa-close"></i> {{ $error }}</div>
#endforeach
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>Success</h4>
{{ $message }}
</div>
#endif
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title text-green"><b>Add Schedule</b></h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<div class="box-body">
{!! Form::model($doctors, ['method' => 'PATCH','route' => ['manageschedule.update', $doctors->doctor_id],'class' => 'form-horizontal','files'=>true]) !!}
<div class="form-group">
<label class="col-md-3 control-label"> Select Doctor :</label>
<div class="col-md-5">
<select class="form-control" required name="doctor_name">
<?php $results = DB::select(DB::raw("SELECT day FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' Order BY id DESC ")); ?>
<option value="{{$doctors->doctor_name}}" SELECTED="YES">{{$doctors->doctor_name}}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" required> Day :</label>
<div class="col-md-5">
<div class="md-checkbox-inline">
<?php $day = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'); ?>
#foreach($day as $days)
<input name="day[]" value="<?php echo $days; ?>" type="checkbox" class="md-checkbox" <?php
foreach ($results as $row) {
if ($row->day == $days) {
echo 'checked="checked"';
} else {
}
}
?> >
<label for="checkbox7"> <?php echo $days; ?> </label>
#endforeach
</div>
</div>
</div>
<?php foreach ($results as $row) { $d=$row->day;}
$result= DB::select(DB::raw("SELECT * FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' And day='".$d."' "));
?>
<div class="form-group">
<label class="col-md-3 control-label" required>Time slots</label>
<div class="col-md-6">
<table class="table table-bordered" id="employee_table" width="50%" >
<th>Start Time</th>
<th>End Time</th>
<th>Manage</th>
<?php foreach ($result as $key=>$vari) {
$id = $vari->id;
?>
<tr id="row1">
<td><div class="input-group ">
<input type="text" class="form-control" id="time" placeholder="Start Time" name="s_time[]" value="<?php echo $vari->start_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<td><div class="input-group ">
<input type="text" class="form-control" id="time1" placeholder="Start Time" name="e_time[]" value="<?php echo $vari->end_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<?php if ($key == 0) { ?>
<td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' disabled></td>
<?php } else { ?>
<td><span class='delete' id='del_<?php echo $id; ?>'><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' id='del_<?php echo $id; ?>' ></td>
</tr>
<?php }
}
?>
</table>
<a type="button" onclick="add_rows();" class="fa fa-plus-circle btn btn-primary"> Add More Time Slots</a>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"> Per Patient Time :</label>
<div class="col-md-5">
<div class=" input-daterange">
<input type="text" name="p_time" class="form-control" placeholder="Set per patient time" id="time1" value="<?php
echo $result[0]->p_time; ?>">
<span class="help-block"> You can set only minute </span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Visibility :</label>
<div class="col-md-5">
<input type="radio" id="checkbox2_5" value="Yes" name="visible" class="md-radiobtn" <?php
foreach($result as $check)
{
if($check->visibility=='Yes'){ echo 'checked="checked"';}else{}
} ?> >
<label for="checkbox2_5"> Yes </label>
<input type="radio" id="checkbox2_10" value="No" name="visible" class="md-radiobtn" <?php foreach($result as $check)
{
if($check->visibility=='No'){ echo 'checked="checked"';}else{}
} ?>>
<label for="checkbox2_10"> No </label>
</div>
</div>
<br><br>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right"id="submit">Update Schedule </button>
</div>
{!! Form::close() !!}
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time').timepicker();
})
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time1').timepicker();
})
});
</script>
<script type="text/javascript">
function add_rows()
{
$rowno = $("#employee_table tr").length;
$rowno = $rowno + 1;
$("#employee_table tr:last").after("<tr id='row" + $rowno + "'><td><div class='input-group '><input type='text' class='form-control' placeholder='Start Time' name='s_time[]' onclick=showtime('row" + $rowno + "')><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><div class='input-group '><input type='text' class='form-control' id='time1' placeholder='End Time' name='e_time[]'><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' onclick=delete_row('row" + $rowno + "')></td></tr>");
}
function delete_row(rowno)
{
$('#' + rowno).remove();
}
</script>
<script type="text/javascript">
//Variant Deleting script///
$(document).ready(function () {
// Delete
$('.delete').click(function () {
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];
alert('Are you sure you want to delete?');
$.ajax({
url: 'api/ajax',
type: 'delete',
data: {id: deleteid},
success: function (response) {
// Removing row from HTML Table
$(el).closest('tr').css('background', 'tomato');
$(el).closest('tr').fadeOut(800, function () {
$(this).remove();
});
}
});
});
});
</script>
<meta name="_token" content="{!! csrf_token() !!}" />
#endsection
here is my controller of api
Route::post('ajax','Controller#ajax')->name('ajax');
here is my web route:
Route::get('/', function () {
return view('auth.login');
});
Route::post('/', function () {
return view('auth.login')->with('successMsg','Please Select A role .');
});
Route::prefix('admin')->group(function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.home');
Route::resource('managedoctor', 'AddDocController');
Route::resource('managefront', 'AddFrontController');
Route::resource('managepatient', 'AddPatientController');
Route::resource('manageschedule', 'AddScheduleController');
Route::get('/logout', 'Auth\AdminLoginController#logout')->name('admin.logout');
});
Route::prefix('doctor')->group(function() {
Route::get('/login', 'Auth\DoctorLoginController#showLoginForm')->name('doctor.login');
Route::post('/login', 'Auth\DoctorLoginController#login')->name('doctor.login.submit');
Route::get('/', 'DoctorController#index')->name('doctor.home');
Route::get('/logout', 'Auth\DoctorLoginController#logout')->name('doctor.logout');
});
Route::prefix('frontdesk')->group(function() {
Route::get('/login', 'Auth\FrontdeskLoginController#showLoginForm')->name('frontdesk.login');
Route::post('/login', 'Auth\FrontdeskLoginController#login')->name('frontdesk.login.submit');
Route::get('/', 'FrontdeskController#index')->name('frontdesk.home');
Route::get('/logout', 'Auth\FrontdeskLoginController#logout')->name('frontdesk.logout');
});
my issue is resolved now the mistake i have done is i was not using the same route group in which am calling the controller with AUTH method