I am working on dropzone js programmatically. this is My div,
<div class="dropzone" id="my-dropzone">
<div class="dz-message">
<div class="col-xs-8">
<div class="message">
<p>Drop files here or Click to Upload</p>
</div>
</div>
</div>
<div class="fallback">
<input type="file" name="file" multiple>
</div>
</div>
and rpzone class is
// Dropzone class:
var myDropzone = new Dropzone("div#my-dropzone", { url: "/file/post"});
but when I drag and drop images to dropzone box images are preview with cross symbols (not success upload). then how can I fix this problem?
dropzone.confif.js
var total_photos_counter = 0;
Dropzone.options.myDropzone = {
uploadMultiple: true,
parallelUploads: 2,
maxFilesize: 5,
previewTemplate: document.querySelector('#preview').innerHTML,
addRemoveLinks: true,
dictRemoveFile: 'Remove file',
dictFileTooBig: 'Image is larger than 16MB',
timeout: 10000,
init: function () {
this.on("removedfile", function (file) {
$.post({
url: '/images-delete',
data: {id: file.name, _token: $('[name="_token"]').val()},
dataType: 'json',
success: function (data) {
total_photos_counter--;
$("#counter").text("# " + total_photos_counter);
}
});
});
},
success: function (file, done) {
total_photos_counter++;
$("#counter").text("# " + total_photos_counter);
}
};
after long time spending find the solution. problem is {{ csrf_field() }} not configuring in my div tag,
first Add this to your main blade template in the section:
<meta name="csrf-token" content="{{ csrf_token() }}">
and then configure dropzone.config.js file to csrf
Dropzone.options.myDropzone = {
uploadMultiple: true,
parallelUploads: 2,
maxFilesize: 16,
previewTemplate: document.querySelector('#preview').innerHTML,
addRemoveLinks: true,
dictRemoveFile: 'Remove file',
dictFileTooBig: 'Image is larger than 16MB',
timeout: 10000,
init: function () {
this.on("removedfile", function (file) {
$.post({
url: '/images-delete',
data: {id: file.name, _token: $('[name="_token"]').val()},
dataType: 'json',
success: function (data) {
total_photos_counter--;
$("#counter").text("# " + total_photos_counter);
}
});
});
},
success: function (file, done) {
total_photos_counter++;
$("#counter").text("# " + total_photos_counter);
},
sending: function(file, xhr, formData){
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
}
};
now it is working fine with correct url
Related
I am trying to reload the table on every successful quantity change and row deletion in add to cart using ajax. But the table is getting reloaded only once after that no change is being observed.
Here is the code:
<script type="text/javascript">
$(".update-cart").change(function (e) {
e.preventDefault();
var ele = $(this);
$.ajax({
url: '{{ route('update.cart') }}',
method: "patch",
data: {
_token: '{{ csrf_token() }}',
id: ele.parents("tr").attr("data-id"),
quantity: ele.parents("tr").find(".quantity").val()
},
success: function (response) {
$("#cart").load(" #cart");
//alert("This is working");
}
});
});
$(".remove-from-cart").click(function (e) {
e.preventDefault();
var ele = $(this);
if(confirm("Are you sure want to remove?")) {
$.ajax({
url: '{{ route('remove.from.cart') }}',
method: "DELETE",
data: {
_token: '{{ csrf_token() }}',
id: ele.parents("tr").attr("data-id")
},
success: function (response) {
$("#cart").load(" #cart");
}
});
}
});
Button id b1 can be clicked only once, id b2 can be live clicked.
function why(e) {
e.preventDefault();
alert("You clicked " + e.target.id);
$("#myDiv").html('<button id="b1" type="button">Click Me!</button><button id="b2" class="button" type="button">Click Me!</button>');
}
$("#b1").click(why);
$(document).on("click", ".button", why);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv">
<button id="b1" type="button">Click Me!</button><button id="b2" class="button" type="button">Click Me!</button>
</div>
I have a trouble when to upload img using ajax in laravel. I have an error in getClientOriginalExtension() I think that trouble in enctype in ajax because the controller can not read the upload file.
this is my view :
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$('body').on('click', '#saveBtn', function(){
var url;
var registerForm = $("#data-form");
var formData = registerForm.serialize();
$(this).html('saving...');
$('#saveBtn').attr('disabled',true);
$.ajax({
enctype: 'multipart/form-data',
url: '{{ route('blog.store') }}',
type:'POST',
data:formData,
success:function(data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Save Data');
}
});
});
});
</script>
and this is my controller
$name_file = time().'.'.$request->img_thumbnail->getClientOriginalExtension();
$request->img_thumbnail->move(public_path('images'), $nama_file);
create.blade.php
#section('content')
<form id="submitform">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name">
</div>
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="photo" id="photo">
</div>
<button class="btn btn-primary" id="submitBtn" type="submit">
<span class="d-none spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
<span class="">Submit</span>
</button>
</form>
#endsection
#push('custom-scripts')
<script src="{{ asset('js/upload.js') }}"></script>
#endpush
upload.js
$(function () {
$('#submitBtn').on('click', (e) => {
e.preventDefault();
var formData = new FormData();
let name = $("input[name=name]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
var photo = $('#photo').prop('files')[0];
formData.append('photo', photo);
formData.append('name', name);
$.ajax({
url: 'api/store',
type: 'POST',
contentType: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
data: formData,
success: (response) => {
// success
console.log(response);
},
error: (response) => {
console.log(response);
}
});
});
});
Controller
class MyController extends Controller
{
use StoreImageTrait;
public function store(Request $request)
{
$data = $request->all();
$data['photo'] = $this->verifyAndStoreImage($request, 'photo', 'students');
Student::create($data);
return response($data, 200);
}
}
StoreImageTrait
<?php
namespace App\Traits;
use Illuminate\Http\Request;
trait StoreImageTrait
{
public function verifyAndStoreImage(Request $request, $filename = 'image', $directory = 'unknown')
{
if ($request->hasFile($filename)) {
if (!$request->file($filename)->isValid()) {
flash('Invalid image')->error()->important();
return redirect()->back()->withInput();
}
return $request->file($filename)->store('image/' . $directory, 'public');
}
return null;
}
}
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready( function () {
$("form#data-form").on("submit",function (e) {
e.preventDefault();
var formData = new FormData(this);
//Ajax functionality here
$.ajax({
url : '{{route('blog.store')}}',
type : "post",
data : formData,
dataType : 'json',
success:function (data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
}, // success end
contentType: false,
processData: false
}); // ajax end
}); // form submit end
}); //document end
I am new to Laravel. I am using Bootstrap file-input plugin to upload multiple files in Laravel. But in my code, url in the uploadUrl is not called. That means ajax call is not sent to the laravel backend controller and controller method is not called. Could you please help me in resolving this issue? Thank you.
HTML CODE
<div class="form-group">
<label class="col-sm-2 control-label required">FEATURED IMAGES</label>
<div class="col-sm-10">
<input id="featured-file" name="featured-file[]" type="file" multiple class="file-loading">
<p class="notice">Please use to upload 550px width x 670px height images for better view</p>
</div>
</div>
jQuery Code
$("#featured-file").fileinput({
theme: 'fa',
uploadAsync:true,
uploadUrl:"{{ url('/news/uploadimgsaddmode') }}",
uploadExtraData: function() {
return {
_token: '<?php echo csrf_token() ?>',
};
},
allowedFileExtensions: ['jpg', 'png', 'gif','jpeg'],
overwriteInitial: false,
maxFileSize:2000,
maxFilesNum: 10
}).on('fileuploaded', function(event, previewId, index, fileId) {
console.log('File Uploaded', 'ID: ' + fileId + ', Thumb ID: ' + previewId);
}).on('fileuploaderror', function(event, data, msg) {
console.log('File Upload Error', 'ID: ' + data.fileId + ', Thumb ID: ' + data.previewId);
});
Laravel Controller Method
public function uploadimagesaddmode(Request $request){
Session::put('uploaded_files','Hi');
Session::save();
return response()->json(['uploaded' =>'Hi']);
}
And I used some html code to test whether controller method is called or not
<p>#if(Session::has('uploaded_files')) {{ Session::get('uploaded_files') }} #endif</p>
If controller method is called Session values should be printed. But no value is printed.
I found a solution. Thanks for all who responded to my question :)
I edited the jQuery Code. Here's the edited one. It works for me.
$(document).on("ready", function() {
$("#featured-file").fileinput({
theme: 'fa',
allowedFileExtensions: ['jpg', 'png', 'gif','jpeg'],
uploadUrl: "{{ url('news/uploadimgsaddmode') }}",
uploadExtraData: function() {
return {
_token: '<?php echo csrf_token() ?>',
};
},
uploadAsync:true,
overwriteInitial: false,
maxFileSize:2000,
maxFilesNum: 10,
}).on("filebatchselected", function(event, files) {
$("#featured-file").fileinput("upload");
});
});
i try to make upload image with ajax without form, when i am sent data without the image, data successfully submitted to the database, but when i am adding an image, when i try to submit, no response at all,
this is my template code :
<input type="hidden" name="lesson_id" value="{{-- $lessons->id --}}">
<input type="hidden" name="parent_id" value="0"> -->
<div class="form-group">
<label>Komentar</label>
<textarea rows="8" cols="80" class="form-control" name="body" id="textbody0"></textarea>
</div>
<ul class="right">
<input type="file" name="image" id="image" />
<img id="myImg" src="#" />
<button type="button" class="btn btn-primary" onClick="doComment({{ $lessons->id }},0)" >Kirim</button>
and this is my script for submit data :
function doComment(lesson_id, parent_id) {
var body = $('#textbody'+parent_id).val();
var image = $('#image').prop('files')[0];
if (body == '') {
alert('Harap Isi Komentar !')
}else {
var postData =
{
"_token":"{{ csrf_token() }}",
"lesson_id": lesson_id,
"parent_id": parent_id,
"image": image,
"body": body
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
type :'POST',
url :'{{ url("lessons/coments/doComment") }}',
dataType: 'json',
data : postData,
beforeSend: function(){
// Show image container
swal({
title: "Sedang mengirim Komentar",
text: "Mohon Tunggu sebentar",
imageUrl: "{{ asset('template/web/img/loading.gif') }}",
showConfirmButton: false,
allowOutsideClick: false
});
{{-- $("#loader").show(); --}}
},
success:function(data){
if (data.success == false) {
window.location.href = '{{ url("member/signin") }}';
}else if (data.success == true) {
$('#textbody'+parent_id).val('');
swal({
title: "Komentar anda sudah terkirim!",
showConfirmButton: true,
timer: 3000
});
getComments();
}
}
});
}
}
Can any one help me?
postData = new FormData();
if(!!file.type.match(/image.*/)){
postData.append("image", file);
$.ajax({
type : 'POST',
url : '{{ url("lessons/coments/doComment") }}',
data : postData,
dataType: 'json',
processData: false,
contentType: false,
success: function(data){
alert('success');
}
});
}else{
alert('Not a valid image!');
}
I just migrated to a different bootstrap template now my ajax functions is not working and my php file which handles the functions is not appearing in the XHR inspect tool of chrome.
I only have this jquery script ? is this enough for running an ajax function? I
<!-- Jquery Core Js -->
<script src="../dashboard-assets/plugins/jquery/jquery.min.js"></script>
HTML CODE
<form id="upload_book_form" method="POST">
<p>Upload Books</p>
<input type="file" id="uploadbookinfo" name="uploadbookinfo" value="Import" />
</form>
SCRIPT FUNCTION
<script type="text/javascript">
$(document).ready(function() {
//upload book
$('#uploadbookinfo').change(function() {
$('#upload_book_form').submit();
});
$('#upload_book_form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Book Added , Try refreshing the page',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else if (getdata == "ERRORFILETYPE") {
swal({
title: 'Oops...',
text: 'File type is not supported',
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-info",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
});
});
</script>