Ajax request for delete image doesnt work in laravel - ajax

I want to delete the image in the preview box, as well as delete it in the database using ajax. Deleting the image in the preview box was successful, but deleting it from the database didn't work.
here my ajax:
$(document).ready(function() {
document.getElementById('pro-image').addEventListener('change', readImage, false);
$(".preview-images-zone").sortable();
$(document).on('click', '.image-cancel', function() {
let no = $(this).data('no');
let idData = $(this).data('id');
$(".preview-image.preview-show-" + no).remove();
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}',
data: {
'id': idData
},
success: function(data) {
alert('success');
}
});
});
});
My Html:
<!-- Percobaan Preview -->
<fieldset class="form-group">
<div class="offset-md-2 col-md-6">
Upload Gambar
<input type="file" id="pro-image" name="gambarku[]" style="display: none;" class="form-control" multiple>
</div>
</fieldset>
<div class="preview-images-zone offset-md-2 col-md-8">
<!-- Gambar Utama -->
<div class="preview-image preview-show-1">
<div class="image-cancel" data-no="1">x</div>
<div class="image-zone"><img id="pro-img-1" src="{{asset('storage/rumah/'.$rumahku->gambar_rumah)}}"></div>
</div>
<!-- Gambar Tambahan -->
<?php $counter = 2 ?>
#foreach($rumahku->gambar as $rows)
<div class="preview-image preview-show-{{$counter}}">
<div class="image-cancel" data-no="{{$counter}}" data-id="{{$rows->id_gambar}}">x</div>
<div class="image-zone"><img id="pro-img-{{$counter}}" src="{{asset('storage/rumah/'.$rows->gambar_unit)}}"></div>
</div>
<?php $counter++ ?>
#endforeach
</div>
<!-- /preview -->
my route
Route::post('unit/API/simpan/{id}', 'partner\UnitController#simpanGambar');
my controller
public function simpanGambar($id)
{
$gambar = Gambar::find($id);
$gambar->delete();
}

you can try this
Route::post('unit/API/simpan', 'partner\UnitController#simpanGambar');
and
public function simpanGambar(Request $request)
{
$gambar = Gambar::find($request->id);
$gambar->delete();
}
or in ajax
$.ajax({
type: 'POST',
url: '{{url("unit/API/simpan")}}' +'/'+ id, <---------- pass id here

Related

Why my page gets refresh while deleting image on 'product edit page'?

VIEW FILE
<div class="col-sm-4">
<label>Other Images</label>
<div class="input-group control-group img_div form-group" >
<input type="file" name="image[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success btn-add-more" type="button">Add</button>
</div>
</div>
</div>
<div>#foreach($image as $image)
<p><img src="{{asset('/files/'.$image->images)}}" height="50px" id="{{$image->id}}" class="photo"/>
<button class="removeimg" data-id="{{$image->id}}" data-token="{{ csrf_token() }}">Remove</button></p>
#endforeach
</div>
AJAX
$(document).ready( function () {
$(document).on('click', '.removeimg',function(){
var confirmation = confirm("are you sure to remove this record?");
if (confirmation) {
var id = $(this).data("id");
// console.log(id)
var token = $(this).data("token");
var $obj = $(this);
$.ajax(
{
url: "{{ url('image/delete') }}/"+id,
type: 'post',
dataType: "JSON",
data: {
"id": id,
"_token": token,
},
success: function (res)
{
// $(this).parents('.photo').remove();
$obj.parents('.photo').remove();
console.log("it Work", res);
}
});
console.log("It failed");
}
});
});
CONTROLLER
public function imgdelete($id){
Image::find($id)->delete($id);
return response()->json([
'success'=> 'Image deleted successfully!'
]);
}
When I delete the image, page gets redirected to product listing. Page should not get refresh when I delete the image. Can you please help me with correction?? NOTE: This process takes place on editproduct page.
You can prevent the default event for the button:
$(document).on('click', '.removeimg',function(event){
event.preventDefault();
.....
});

Laravel How to handle file upload: Can't save image filename

So I want to upload a picture but it only store its description correctly. The file is stored as "noimage.jpg" which means the filename isn't read. I'm using modal btw. My database is named galleries and the migration contains these:
$table->id();
$table->timestamps();
$table->string('upload');
$table->longtext('description')->nullable();
CONTROLLER:
public function store(Request $request)
{
$galleries=new Gallery;
// Handle File Upload
if($request->hasFile('upload')){
// Get filename with the extension
$filenameWithExt = $request->file('upload')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('upload')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.$extension;
// Upload Image
$path = $request->upload('upload')->storeAs('public/upload', $fileNameToStore);
// make thumbnails
$thumbStore = 'thumb.'.$filename.'_'.time().'.'.$extension;
$thumb = Image::make($request->file('upload')->getRealPath());
$thumb->save('storage/upload/'.$thumbStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$galleries->description = $request->input('description');
$galleries->upload = $fileNameToStore;
$galleries->save();
}
FORM:
<form id="uploadForm">
<div class="modal-body">
<input type="hidden" name="id" id="id">
<!-- Upload image input-->
<div class="input-group mb-3 px-2 py-2 rounded-pill bg-secondary shadow-sm">
<input type="file" name="upload" id="upload" onchange="readURL(this);" class="form-control border-0">
<label id="upload-label" for="upload" class="font-weight-light text-muted">Choose file</label>
<div class="input-group-append">
<label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i class="fa fa-cloud-upload mr-2 text-muted"></i><small class="text-uppercase font-weight-bold text-muted">Choose file</small></label>
</div>
</div>
<!-- Uploaded image area-->
<p class="font-italic text-white text-center">The image uploaded will be rendered inside the box below.</p>
<div class="image-area mt-4 bg-white"><img id="imageResult" src="#" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
<label>Caption</label>
<input type="textarea" class="form-control text-white" name="description" id="description">
</div>
</form>
AJAX
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//ADD PICTURE
$('#btnUpload').click(function(){
$('#uploadModal').modal('show');
});
$('#btnSave').click(function(){
$.ajax({
data: $('#uploadForm').serialize(),
url: "{{ route('home.store') }}",
type: "POST",
dataType: 'json',
success: function(data){
$('#uploadModal').modal('hide');
},
error: function(data){
console.log('Error:', data);
}
});
});
//Image reader to show pic when selected
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageResult')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(function () {
$('#upload').on('change', function () {
readURL(input);
});
});
var input = document.getElementById( 'upload' );
var infoArea = document.getElementById( 'upload-label' );
input.addEventListener( 'change', showFileName );
function showFileName( event ) {
var input = event.srcElement;
var fileName = input.files[0].name;
infoArea.textContent = 'File name: ' + fileName;
}
});
</script>
Assuming you're using ajax to upload the file, you'll need to use a FormData object instead of .serialize()
$.ajax({
data: new FormData($('#uploadForm').get(0)), // use formdata object
url: "{{ route('home.store') }}",
type: "POST",
dataType: 'json',
contentType: false, // required for
processData: false, // jquery ajax file upload
success: function(data){
$('#uploadModal').modal('hide');
},
error: function(data){
console.log('Error:', data);
}
});
You don't add "enctype" in form tag.
Change your code:
<form id="uploadForm">
with:
<form id="uploadForm" enctype='multipart/form-data'>
If this above not working then:
1.install this package by following command:
composer require "laravelcollective/html":"^5.2.0"
2.In config/app add this line:
'providers' => [
// ...
**Collective\Html\HtmlServiceProvider::class,**
// ...
],
and
'aliases' => [
// ...
**'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,**
// ...
],
3.Change Form:
{!! Form::open([ 'action'=> 'NameofController#store', 'method' => 'POST','enctype' => 'multipart/form-data' ]) !!}
<div class="form-group">
{{Form::text('name','' , ['class' =>'form-control'])}}
</div>
<div class="form-group">
{{Form::text('phone','' , ['class' =>'form-control', 'placeholder' => 'phone' ])}}
</div>
<div class="form-group">
{{Form::file('image_name')}}
</div>
{{Form::submit('Submit' , ['class' =>'btn btn-primary' ])}}
{!! Form::close() !!}
you can this way to store your file with custom name:
$path = $request->file('upload')->store('public/upload/' .$fileNameToStore);

How to pass a parameter from a view to the controller with Ajax? Codeigniter

I am just learning and I would like you to help me solve this problem: I have two views, in view 1 it shows me a list of users, when clicking on any of them you must open another view showing the information about that user in view 2 .
To do that in view 1 with js I capture the user's id and send it to the controller by ajax, and in the controller it sends it to the model and the model response returns to the controller and sends it to view2, to show only the information of the selected user, the question is that it does not work, could you help me, what am I doing wrong?
View 1: This is the paragraph where you click and capture the id and the ajax that sends that id to the controller.
View1
<p onclick="detalles('<?=$p->usuarioId?>');"> <?=$p->usuarioId?><i class="fa fa-check-circle"></i> <?php echo $p->user ?></p>
<script>
function detalles(id=null){
$ (document) .ready (function () {
console.log(id);
$.ajax({
type: "POST",
data : {'id': id},
dataType:"html",
url: "usuarios_admin/ver",
success: function(result)
{
alert("good");
console.log("result",result);
}
});
});
}
</script>
Controller
public function ver(){
$id = $this->input->post("id");
if($id != null) {
$data = $this->PostUser->find($id);
echo json_encode($data);
$this->load->view('usuarios/vista2', $data);
}
}
model:
function find($id){
$this->db->select();
$this->db->from($this->table);
$this->db->where($this->table_id, $id);
$query = $this->db->get();
return $query->row();
}
view2:
here you must see the user data
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 lininfo">
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5 sinpa">
<p class="colorp">Name:</p>
</div>
<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 sinpa">
<p class="colorpi"><?php $data['name'] ?></p>
</div>
</div>
try this, i think there should be typo mistake
<p onclick="detalles('<?php echo $p->usuarioId ?>');"> <?php echo $p->usuarioId; ?>
<i class="fa fa-check-circle"></i> <?php echo $p->user ?></p>
Is your 2nd view load after ajax call?
Have you print your return data in ajax success,because you define dataType:"html" in ajax but you return json data from controller.
Thank you for your answers, it came out.
I had to print on the view this way to see the data:
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 lininfo">
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5 sinpa">
<p class="colorp">Name :</p>
</div>
<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 sinpa">
<p class="colorpi"><?php echo $user->name ?></p>
</div>
</div>
controller:
public function ver(){
$id = $this->input->post("id");
if($id != null) {
$data['user'] = $this->PostUser->find($id);
$this->load->view('usuarios/vista2', $data);
}
}
ajax y view 1
<div class="hi">
<!-- here you would see the result of ajax -->
<div>
<script>
function detalles(id=null){
$ (document) .ready (function () {
console.log(id);
$.ajax({
type: "POST",
data : {'id': id},
dataType:"html",
url: "usuarios_admin/ver",
success: function(result)
{
$('.hi').html(result);
}
});
});
}
</script>

Using ng-repeat after $http call

I'm learning Angular (1.6.6), so I'm hoping/assuming I'm missing something basic.
I'm populating a drop-down menu on ng-init, which is working as expected. I'm returning JSON from the DB, and console.log() shows me that the JSON is pulling through as expected.
I'm stuck with ng-repeat, trying to display the data in another div.
My Controller
app.controller('RandomTownCtrl', [
'$scope',
'$http',
function($scope, $http){
window.MY_SCOPE = $scope;
$scope.getAllRegions = function() {
$http({
method: 'GET',
url: '/all-regions'
}).then(function successCallback(response) {
$scope.regions = response.data;
}, function errorCallback(response) {
console.log('error');
});
};
$scope.getRandomTown = function() {
var guidEntity = $scope.guidEntity;
if (typeof guidEntity === 'undefined') { return };
$http({
method: 'GET',
url: '/region-name?region-guid=' + guidEntity
}).then(function successCallback(response) {
$scope.randomTown = response.data;
console.log($scope.randomTown);
}, function errorCallback(response) {
});
};
}
]);
The Markup
<div class="column col-sm-5 content-column">
<form ng-controller= "RandomTownCtrl" ng-init="getAllRegions()" ng-submit="getRandomTown()">
<h3>Generate Random Town</h3>
<div class="form-group">
<select name="nameEntity"
ng-model="guidEntity"
ng-options="item.guidEntity as item.nameEntity for item in regions">
<option value="" ng-if="!guidEntity">Choose Region</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Generate!</button>
</form>
</div>
<div class="column col-sm-5 content-column" id="output-column">
<div class="header">
<h4>Region Name:</h4>
</div>
<div ng-controller='RandomTownCtrl'>
<p ng-repeat="item in randomTown">
{{ item.name_region }}
</p>
</div>
</div>
You are mixing $scope and self together, you need also ng-repeat needs an array not an object.
$scope.randomTown = response.data;
Beginner Angular mistake: I didn't understand that the ng-controller directive created an isolate scope, and the output I was expecting wasn't happening because the data simply wasn't there in that scope.

Adding records to a drop down menu without form refresh

I want to add records to a drop down menu without form refresh. I'm using codeigniter and bootstrap
Here is the Bootstrap Modal :
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
<h4 id="myLargeModalLabel" class="modal-title">Add Record</h4>
</div>
<div class="modal-body">
<form class="sky-form" id="sky-inchidere" method="post" accept-charset="utf-8" action="">
<dl class="dl-horizontal">
<dt>Name<span class="color-red">*</span></dt>
<dd>
<section>
<label class="input">
<i class="icon-append fa fa-inbox"></i>
<input type="text" value="" name="name" required>
<b class="tooltip tooltip-bottom-right">Add New Record</b>
</label>
</section>
</dd>
</dl>
<hr>
<button type="submit" class="btn-u" style="float:right; margin-top:-5px;">Submit</button>
</form>
</div>
</div>
</div>
Ajax script :
$(document).ready(function(){
$("#sky-inchidere").submit(function(e){
e.preventDefault();
var tdata= $("#sky-inchidere").serializeArray();
$.ajax({
type: "POST",
url: 'http://localhost/new/oportunitati/add',
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
},
error: function (XHR, status, response) {
alert('fail');
}
});
});
});
CI Controller ( i have added the modal code here for test )
public function add() {
$tdata = array( name=> $this->input->post(name),
);
$this->db->insert('table',$tdata);
}
When i use this code i get "fail" error message.
Thanks for your time.
how yo debug:
1. Print your 'tdata' and see what happen;
2. Something wrong here: $this->input->post('name');
Try to use:
$tdata = array(
'name' => $this->input->post('name')
);
I manage to find the problem and correct it. (typo on the table name)
Now I have come across a different problem. In the ajax success I cant refresh the chosen dropdown records i have tried :
success:function(tdata)
{
// close the modal
$('#myModal').modal('hide');
// update dropdown ??
$('.chosen-select').trigger('liszt:updated');
$('#field-beneficiar_p').trigger('chosen:updated');
$('#field-beneficiar_p').trigger('liszt:updated');
},
Any help in how i can refresh the records to see the last added item will be appreciated. I'm using chosen plugin.
from controller send data in json_encode
then in js function
$.ajax({
type: "POST",
url: "<?php echo base_url('login/get_time'); ?>",
data: {"consltant_name": consltant_name, "time": time},
success: function(data) {
var data = JSON.parse(data);
var options = '';
options = options + '<option value="">Please Select One</option>'
$.each(data, function(i, item) {
options = options + '<option value="' + item + '">' + item + '</option>'
});
selectbox.html(options);
}});

Resources