Laravel upload image through modal not working - javascript

Im making an inventory system in laravel and I want to upload an image every products that I have. My problem is I cant upload an image. I tried my old code in uploading photo and it is not working in my current project. The upload code you see in the controller is in a laravel collective form. But now, I am using a modal and an ajax request to save the inputs into the database. Can someone know what should I do about this? Btw, my modal doesnt have a form tag because I thought forms will not work in modals. Thanks in advance!
Modal Create.
<div class="modal fade" id="exampleModalCenter" 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">
<h5 class="modal-title" id="exampleModalCenterTitle">Register New Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p style="font-weight: bold;">Name </p>
<input type="text" class="form-control" id="product_name"/>
<p style="font-weight: bold;">Description </p>
<input type="text" class="form-control" id="description"/>
<p style="font-weight: bold;">Price </p>
<input type="text" class="form-control" id="currentprice"/>
{{-- <input style="text-transform:uppercase" type="text" class="form-control" id="supplier_id"/> --}}
<p style="font-weight: bold;">Supplier </p>
<select class="form-control" id="supplier_id" >
#foreach ($suppliers as $supplier)
<option value="{{$supplier->id}}">{{$supplier->name}}</option>
#endforeach
</select>
<p style="font-weight: bold;">Picture </p>
<input type="file" class="form-control" id="picture"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="add_product">Add</button>
</div>
</div>
</div>
</div>
Controller
public function store(Request $request)
{
$data = $request->all();
$data['product_name'] = ($data['product_name']);
$data['description'] = ($data['description']);
$data['supplier_id'] = ($data['supplier_id']);
$data['price'] = ($data['price']);
if ($request->hasFile('image')){
//Add new photo
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('img/' . $filename);
Image::make($image)->resize(300,300)->save($location);
$oldFilename = $products->image;
//Update DB
$products->image = $filename;
//Delete the old photo
// Storage::delete($oldFilename);
}
Product::create($data);
return response()->json($data);
}
Ajax
$(document).ready(function(){
//add
$('#add_product').click(function(e){
e.preventDefault();
var name = $('#product_name').val();
var description = $('#description').val();
var price = $('#currentprice').val();
var supplier_id = $('#supplier_id').val();
var image = $('#picture').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ url('/product') }}",
method: 'post',
data:{
product_name: name,
description: description,
price: price,
supplier_id: supplier_id,
image: image,
},
success: function (res){
console.log(res);
window.location.href = '{{route("products")}}'
}
});
});
//add
Model
class Product extends Model
{
use SoftDeletes;
protected $fillable = [
'product_name', 'quantity', 'description' ,'supplier_id', 'price', 'image',
];
public function supplier()
{
return $this->hasOne('App\Supplier');
}
}

I Can’t add a comment, that is dumb ...
Your also going to likely need to encode the image data in the json.
See How do you put an image file in a json object?
(Fixed wording)

Related

I am trying to upload video in laravel but not able to do so

Here is the Ajax part to add the video Url in the database.I am getting the value of Video title and video desc in database but not getting the url.
<div class="modal fade" id="addVideo" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-headerr">
<h5 class="modal-title" id="exampleModalLabel" data-toggle="modal">Add New Video</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="alert alert-danger" style="display:none"></div>
<form class="image-upload" method="post" action="" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Title</label>
<input type="tetx" name="addvideoTitle" id="AddvideoTitle" placeholder="Add a title"
class="form-control" />
</div>
<div class="form-group">
<label>Discription</label>
<input type="text" name="Addvideodesc" id="Addvideodesc" placeholder="Add a discription"
class="form-control" />
</div>
<div class="form-group">
<label>Add a video</label>
<input type="File" name="add-video" id="add-video" placeholder="Add a video to upload"
class="form-control" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="saveNewVideo">Save</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$(document).on('click','#saveNewVideo',function(){
var add_videotitle= $('#AddvideoTitle').val();
var add_videoDesc= $('#Addvideodesc').val();
var add_video= $('#add-video').val();
$.ajax({
type: "POST",
dataType: "json",
url: '{{ url('/event/saveEvent') }}',
data: {
'add_videoDesc': add_videoDesc,
'add_videotitle': add_videotitle,
'add_video':add_video,
_token: '{{csrf_token()}}'
},
success: function (data){
}
});
});
});
</script>
Controller code is written for adding video url in database I have written the value and getting the response but not actually saving the data in database.
public function saveEvent(request $request){
try{
if(!$request->ajax())
throw new \Exception('Not a valid Request');
$event =new Event();
$event->user_id=Auth::user()->id;
$event->event_name=$request->event_name;
$event->date=$request->event_date;
$event->time=$request->event_time;
$event->location=$request->event_location;
$event->cost=$request->event_cost;
$event->join_url=$request->event_join;
$event->add_video_title=$request->add_videotitle;
$event->add_video_desc=$request->add_videoDesc;
if($request->hasfile('add_video'))
{
$image = $request->file('add_video');
$extention= $image->getClientOriginalExtension();
$filename = time() . '.'. $extention;
$path = public_path('video');
$image->move('assets/video', $filename);
$imageurl=$path."/". $filename;
$event->video = $filename;
}
$event->save();
return response()->json(['status'=>true,'message'=>'Event Added Successfully','data'=>$event]);
}//end here try
catch(\Exception $e)
{
return response()->json(['status'=>false,'message'=>$e->getMessage()]);
}
}
According to Laravel Docs, in the case of Ajax calls - you could, for example, store the token in an HTML meta tag::
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type="text/javascript">
// and then include in your ajax header like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#saveNewVideo').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$.ajax({
type:'POST',
url: '{{ url('/event/saveEvent') }}',
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response) {
this.reset();
alert('Video has been uploaded successfully');
}
},
error: function(response){
$('#file-input-error').text(response.responseJSON.message);
}
});
});
</script>
That code is checking for the extension but not the MIME type. You should use the appropriate MIME type:
Video Type Extension MIME Type
Flash .flv video/x-flv
MPEG-4 .mp4 video/mp4
iPhone Index .m3u8 application/x-mpegURL
iPhone Segment .ts video/MP2T
3GP Mobile .3gp video/3gpp
QuickTime .mov video/quicktime
A/V Interleave .avi video/x-msvideo
Windows Media .wmv video/x-ms-wmv
If you are not sure about the MIME type of the file you are testing you can try $file->getMimeType()
public function store(Request $request)
{
$request->validate([
'video' => 'mimetypes:video/x-ms-asf,video/x-flv,video/mp4,application/x-mpegURL,video/MP2T,video/3gpp,video/quicktime,video/x-msvideo,video/x-ms-wmv,video/avi|max:204800'
]);
if($request->hasfile('add_video')) {
$unique_id = strtolower(str_replace('.', '', uniqid('', true)) . time());
$videoFile = $request->file('add_video');
$extension = $videoFile->getClientOriginalExtension();
$fileNameToStore = $unique_id . '.' . $extension;
$filepath = $videoFile->storeAs('video', $fileNameToStore);
$event->video = $filepath;
}
$event->save();
}
Store Files in Storage Folder
$file->storeAs('files', $fileName);
// storage/app/files/file.pdf
Store Files in Public Folder
$file->move(public_path('files'), $fileName);
// public/files/file.pdf
To display data on the front-end side.
$videoPath = !empty($pp_question->video) && Storage::exists($pp_question->video) ? Storage::url($pp_question->video) : asset(Storage::url('default/video.mp4');

Ajax file upload in PHP using javascript popup [duplicate]

This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 3 years ago.
I am having problem with uploading file with JavaScript Popup. This is my first experience to upload file with such JavaScript popup. I don't know how to pass the input[type:file] to the ajax function and then send to the php file for uploading.
This is the button which calls the popup:
<a class="btn btn-primary btn-sm" data-toggle="modal" data-target="#uploadDocument">Upload Document</a>
<div class="modal fade" id="uploadDocument" role="dialog">
<div class="modal-dialog" style="top: 20%;">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header" style="background-color: #367FA9">
<h4 class="modal-title" id="myModalLabel" style="color:white">Upload Document</h4>
</div>
<!-- Modal Body -->
<div class="modal-body" style="padding-top: 20px; padding-right: 40px; padding-left: 40px;">
<!-- <img src="police/images/new.jpg" width="120px" height="100px"> -->
<p id="uploadMD"></p>
<form role="form" id="uploadForm" >
<div class="form-group">
<input type="hidden" name="" id="rowid" value="<?php echo $id; ?>">
</div>
<div class="form-group">
<label>Document Name</label>
<input type="text" name="" id="documentName" class="form-control">
</div>
<div class="form-group">
<label>Document</label>
<input type="file" class="form-control" placeholder="Please Select File" id="documentFile">
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary submitBtn block" style="background-color: #367FA9" onclick="uploadDocument()" style="width: 100%;">Upload Document</button>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The javascript code is as follows:
<script>
function uploadDocument(){
var rowid = $('#rowid').val();
var documentName = $('#documentName').val();
var documentFile = $('#documentFile').val();
if(documentName.trim() == '' ){
alert('Please write file name');
$('#documentName').focus();
return false;
}else if(documentFile.trim() == '' ){
alert('Please Select File');
$('#documentFile').focus();
return false;
}else {
$.ajax({
method:'POST',
url:'upload.php',
enctype: 'multipart/form-data',
data:'&rowid='+rowid+'&documentName='+documentName+'&documentFile='+documentFile,
success: function(result){
$('#uploadForm').trigger('reset');
if(result == '1'){
$('#uploadMD').html('<span style="color:green;">Your File is uploaded. Thank you</span>');
setTimeout(function(){ window.location.reload() }, 5000);
}
else{
$('#uploadMD').html('<span style="color:red;">Uploading Problem</span>').fadeIn().delay(5000).fadeOut();
}
}
});
}
}
</script>
and the upload.php file is here:
<?php
$rowid = $_POST['rowid'];
$documentName = $_POST['documentName'];
$file_name = $_FILES['documentFile']['name'];
$file_move = move_uploaded_file($file_tmp,"../uploads/ps/".$file_name);
include "../include/configs.php";
if ($file_move) {
$q2 = "UPDATE requests SET support_doc='$file_name' WHERE slug='$id'";
$query = mysqli_query($con, $q2);
if ($query) {
echo $success = 1;
}
}
?>
Thanks in advance.
Try formdata to pass in php file ajax call
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
Thanks

Load DataTable data to a Edit Modal

I am trying to create an edit function for my data table. The data table is created using Yajra Data tables. Everything working fine unless when I try to load existing data into the edit modal it fails. No error is showing but the modal does not launch. I have only included a little portion of my code here for easy reference.
Modal:
<!-- Update Status Model Box -->
<div id="updateStatusModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content bg-default">
<div class="modal-body">
<form class="form-horizontal" id="updateStatus">
#csrf
#method('PUT')
<div class="row">
<div class="col">
<div class="form-group text-center">
<h6 class="font-weight-bold">Stage 1</h6>
<label for="stage_1" class="switch">
<input type="checkbox" class="form-control" id="stage_1">
<div class="slider round"></div>
</label>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<div class="col-md">
<label for="firstname">Coding</label>
<input type="text" class="form-control" id="first_name" value="" placeholder="Enter Completed Page Count">
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer justify-content-between">
<button type="button" name="update_btn" id="update_btn" class="btn btn-outline-warning">Update</button>
</div>
</div>
</div>
</div>
jquery funtion:
// Edit action
$(document).on('click', '.updateStatus', function(){
$tr = $(this).closest('tr');
var data = $tr.clidren("td").map(function(){
return $(this).text();
}).get();
console.log(data);
$('#id').val(data[0]);
$('#job_id').val(data[2]);
$('#stage_1').val(data[3]);
$('#conversion').val(data[4]);
$('#updateStatusModal').modal('show');
});
I tried this method I found but this is not working. Can anyone provide me any pointers here?
I've just didn't seen your front scripts (also back-end codes), but instead I can share my implementation for that you need. It works perfectly like showed in this (screenshot).
Here I'll put front and back codes. There is functionality for editing existsing Datatable record, also record deletion.
FRONT
<!--HERE ATTACH NECESSARY STYLES-->
<!--VIEW end-->
<link rel="stylesheet" type="text/css" href="{{ asset('css/admin/datatables.min.css') }}"/>
<table id="yajra_datatable" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Options</th>
</tr>
</thead>
</table>
<div class="modal modal-danger fade" id="modal_delete">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Delete Language</h4>
</div>
<div class="modal-body">
<p>Are You sure You want to delete this Language?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="delete_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<div class="modal modal-warning fade" id="modal_edit">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Edit Language</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="language_name">Language Name</label>
<input name="language_name" id="language_name" type="text" value="" class="form-control" placeholder="Language Name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="edit_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<input type="hidden" id="item_id" value="0" />
<!--VIEW end-->
<!--HERE ATTACH NECESSARY SCRIPTS-->
<!--SCRIPTS start-->
<script src="{{ asset('js/admin/jquery.dataTables.min.js') }}"></script>
<script type="text/javascript">
var YajraDataTable;
function delete_action(item_id){
$('#item_id').val(item_id);
}
function edit_action(this_el, item_id){
$('#item_id').val(item_id);
var tr_el = this_el.closest('tr');
var row = YajraDataTable.row(tr_el);
var row_data = row.data();
$('#language_name').val(row_data.name);
}
function initDataTable() {
YajraDataTable = $('#yajra_datatable').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('admin.book_languages.ajax') }}",
"columns":[
{
"data": "name",
"name": "name",
},
{
"data": "",
"name": ""
},
],
"autoWidth": false,
'columnDefs': [
{
'targets': -1,
'defaultContent': '-',
'searchable': false,
'orderable': false,
'width': '10%',
'className': 'dt-body-center',
'render': function (data, type, full_row, meta){
return '<div style="display:block">' +
'<button onclick="delete_action(' + full_row.id + ')" type="button" class="delete_action btn btn-danger btn-xs" data-toggle="modal" data-target="#modal_delete" style="margin:3px"><i class="fa fa-remove"></i> Delete</button>' +
'<button onclick="edit_action(this, ' + full_row.id + ')" type="button" class="edit_action btn btn-warning btn-xs" data-toggle="modal" data-target="#modal_edit" style="margin:3px"><i class="fa fa-edit"></i> Edit</button>' +
'</div>';
}
}
],
});
return YajraDataTable;
}
$(document).ready(function() {
var YajraDataTable = initDataTable();
$('#delete_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.delete') }}",
data: {
'item_id': $('#item_id').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#modal_delete').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#edit_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.edit') }}",
data: {
'item_id': $('#item_id').val(),
'language_name': $('#language_name').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (response) {
$('#modal_edit').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#modal_delete').on('hidden.bs.modal', function () {
$('#item_id').val(0);
});
$('#modal_edit').on('hidden.bs.modal', function () {
$('#item_id').val(0);
$('#language_name').val("");
});
});
</script>
<!--SCRIPTS end-->
BACK
public function index() {
return view('admin.book-languages.index');
}
public function ajax() {
$items = BookLanguage::latest('id');
return DataTables::of($items)->make(true);
}
public function delete(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 200); // 404
} else {
$item->delete();
return response()->json([
'success' => true,
'message' => 'Item successfully deleted.',
], 200);
}
}
public function update(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 404);
} else {
$item->name = $request->get('language_name');
$item->save();
return response()->json([
'success' => true,
'message' => 'Item successfully updated.',
], 200);
}
}
ROUTES
// ...
// book_languages
Route::group(['prefix' => 'book-languages', 'as' => 'admin.book_languages.',], function () {
Route::get('all', 'BookLanguageController#index')->name('index');
Route::get('ajax', 'BookLanguageController#ajax')->name('ajax');
Route::post('update', 'BookLanguageController#update')->name('edit');
Route::post('delete', 'BookLanguageController#delete')->name('delete');
});
// ...
I think this can help you and others to build wanted functionality. Here this could be also with more hint-comments, but as it not small, I can answer later via post comments.
i am building a Laravel ERP-like web application and am implementing a CRUD function modal like you. I have made mine a server-side processing application with resource APIs in Laravel. Well, please be reminded that i have cut the #extends(layout.app) & #section('stylesheet') parts to go right into the answer. You should extend them in your own application to make everything work.
View.blade script
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('#customertable').DataTable({
processing: true,
serverSide: true,
dom: 'B<"top"frli>tp',
ajax: {
url: "{{ route('customer.index') }}", //Accessing server for data
columns: [
{data: 'id'}, //data refers to DB column name
{data: 'name'},
{data: 'chiname'},
{data: 'type'},
{data: 'action'}, //this is an addColumn item from Controller
]
});
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Control the modal behavior when clicking the edit button.
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Create a brand-new record
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Update
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Save
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#customerForm').serialize(),
url: "{{ route('customer.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#customerForm').trigger("reset");
$('#customermodal').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Error');}
});
});
//Delete
$('body').on('click', '.deletecustomer', function () {
var id = $(this).data("id");
confirm("Are You sure?");
$.ajax({
type: "DELETE",
url: "{{ route('customer.store') }}"+'/'+id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
</script>
View.blade html-table & modal part
#section('content')
<div class="container">
<div class="card-header border-left"><h3><strong> Customer overview</strong></h3></div>
<br>
<div class="row">
<div class="col-md text-right">
<button type="button" class="btn btn-success" data-toggle="modal" href="javascript:void(0)" id="createNewcustomer">Create Record</button>
</div>
</div>
{{-- Modal --}}
<div id="customermodal" class="modal fade" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times</span></button></div>
<div class="modal-body">
<form id="customerForm" name="customerForm" class="form-horizontal">
<input type="hidden" name="customerid" id="customerid">
<div class="form-group">
<label for="name" class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="chiname" name="chiname" placeholder="Customer Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Contract type</label>
<div class="col-sm-12">
<select name="type" id="type" class="form-control">
<option value="" disabled>Type</option>
<option value="Government">Government Contract</option>
<option value="Private">Private Contract</option>
</select>
</div></div>
<br>
<div class="col-sm text-right">
<button type="submit" class="btn btn-outline-secondary" id="saveBtn" value="create">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
{{-- Table --}}
<br>
<div class="row">
<br/>
<br/>
<div class="form-group col-md-12 align-content-center">
<table class="table-fluid center-block" id="customertable">
<thead>
<tr>
<th>id</th>
<th>ChiName</th>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
#endsection
CustomerController
public function index(Request $request)
{
$customers = Customer::all();
}
return Datatables::of($customers)
->addColumn('action', function($customer){
$btn = 'Edit';
$btn = $btn.' Delete';
return $btn;})
->rawColumns(['action'])
->make(true);
}
return view('customer.Customer'); //my view blade is named Customer under customer dir. put your blade destination here.
}
public function store(Request $request)
{
Customer::updateOrCreate(['id' => $request->customerid],
['name' => $request->name, 'chiname' => $request->chiname,'type' =>$request->type]);
return response()->json(['success'=>'Product saved successfully.']);
}
public function edit($id)
{
$customer = Customer::findorfail($id);
return response()->json($customer);
}
public function destroy($id)
{
Customer::findorfail($id)->delete();
return response()->json(['success'=>'Product deleted successfully.']);
}
Model (pick either A.) $guarded = [] OR B.) $fillable = ['fields','fields'] as you like)
class Customer extends Model
{
protected $fillable = ['name','chiname','type'];
}
web.api (route setting)
Route::resource('customer', 'CustomerController')->middleware('auth');
Migration / DB schema structure
class CreateCustomersTable extends Migration
{
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('chiname');
$table->string('type');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('customers');
}
I have not included any protection in it like gate, auth or so. But basically this is the skeleton of doing CRUD with dataTable in Laravel framework with both JS, Ajax, Jquery, PHP all in one. Kindly be reminded that the queries for such CRUD actions are directly linked to the Database server. If you want to show data processed by the DataTable, use your own jquery function to fetch and show them on the modal. My answer is not the best but i hope it helps you >:)
(I could not post a picture to show you here as i dont have enough reputation lol. gg)

Modal hide trobleshooting

I am working on a module where a dropdown modal has to appear after a duration of 3 mins on the page. It has an input field where digits has to be entered by the user and when he clicks on 'save', the modal should hide. Although I am getting the modal at correct time and when the digits are entered the values are being saved too but only the modal does not hides. I am just unable to figure out the reason behind it as the modal implementation is correct up to my knowledge. I am new to jquery and javascript so need suggestions and expertise of community. I am putting my code here, please have a look and any help or suggestion will be highly appreciated.
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation PIN:</p>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
// $("#spinner").show();
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
//dataType:'json',
success: function(result){
if(result == 'active')
{
$("#bt").html(result) ;
jQuery('#myModal').modal('hide');
}
else if(result == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And the ajax request being made for success,
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
echo trim('active');
Please try console.log your result, you need to know the respond.
console.log(result);
here is the problem: if(result == 'active')
Remove echo trim('active');
change to : header('Content-Type: application/json', true, 200);
echo json_encode('active')); exit();
i hope you get it.

how to refresh and rebind the data from db in angularjs

hi all iam using angularjs ngrepeat to bind the datas into table.i have one add new button when i click bootstrap model popup open i fill the input details click submit means data will stored correctly but table couldn't not get the new data but once i reload the page data will show
my controller code
var refresh = function () {
$http.get('/ViewFacility').success(function (response) {
$scope.ViewFacilitys = response;
};
refresh();
My add new code:
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
refresh();
});
};
Html Code
<form name="profileform">
<div class="modal fade" id="myModal" role="dialog" ng-controller="IndexController">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="margin-top:135px">
<div class="modal-header">
<h4 class="modal-title ">Role Name</h4>
</div>
<div class="modal-body">
<h4>Name</h4>
<input type="text" name="RoleName" class="form-control" ng-model="Role.RoleName">
<span class="error" ng-show="profileform.FirstName.$invalid && profileform.FirstName.$dirty">Please enter a First Name</span>
<h4>Description</h4>
<input type="text" name="Description" class="form-control" ng-model="Role.Description">
<span class="error" ng-show="profileform.LastName.$invalid && profileform.LastName.$dirty">Please enter a Last Name</span>
<h4>IsActive</h4>
<input type="checkbox" name="IsActive" class="form-control checkbox" ng-model="Role.IsActive" style="margin-left:-47%" >
<span class="error" ng-show="profileform.Email.$invalid && profileform.Email.$dirty">Please enter a Email</span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="AddRole()" ng-disabled="profileform.$invalid">Submit</button>
<button class="btn btn-primary" data-dismiss="modal" ng-click="deselect()">Clear</button>
</div>
</div>
</div>
</div>
</form>
Just add the new item to the array.
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
$scope.ViewFacilitys.push($scope.Role);
});
};
You don't need to fetch all data each time you create a new item. Refresh must be called just one time.
For pagination you can code a simple function that send the number of page to the server:
$scope.changePage = function (page) {
$scope.get('/ViewFacility?page='+page)
.then(function (response) {
$scope.ViewFacilitys = response.data;
});
}
Try modifying your refresh function like so
var refresh = function () {
$http.get('/ViewFacility').success(function (response) { //assuming this only fetches the newly added one
$scope.ViewFacilitys.push(response);
};

Categories

Resources