Uploading an image cropped using a cropper.js plugin in laravel - javascript

I have used cropper.js plugin in my application to crop image. I am able to crop the images. Now I am trying to send the images to server and save them. I have updated the the modal window that shows the cropped image as follows:
ent<!-- Modal -->
<div class="modal fade" id="modal" role="dialog" aria-labelledby="modalLabel" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Cropper</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="img-container">
<img id="image" src="" alt="Picture">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>er code here
and i send image to server with Ajax request as following script:
cropper.getCroppedCanvas().toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
$.ajax({
url: 'upload/image-crop',
type: 'GET',
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
and save image in controller as follow:
public function uploadImageCrop(Request $request){
$data = $request->croppedImage;
$data = base64_decode($data);
$image_name= time().'.jpg';
$path = public_path() . "\images\upload\img" . $image_name;
file_put_contents($path, $data);
return response()->json(['success'=>'done']);
}
this work successfully but dont save valid image.

One of the issues may be from trying to upload an image via GET. Try changing the HTTP verb to POST in your ajax request and routes.php
$.ajax({
url: 'upload/image-crop',
type: 'POST',
...

Related

File is stored couple of times instead of once

When I upload a file it is stored X times where X is the time count you upload it. If I try to upload it three times in a row it will store one file, two files, three files which gives us 6 in total.
Why does that happen?
$(function() {
$("#uploadButton").on('click', function() {
const job_id = $(this).attr("data-item");
$("#cvForm").submit(function(e) {
e.preventDefault();
var form_data = new FormData(document.getElementById("cvForm"));
axios({
method: 'post',
url: '/job/apply/' + job_id,
data: form_data,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function(response) {
console.log(response);
}).catch(function(response) {
console.log(response);
});
return false;
});
});
});
Form is:
<div class="modal fade" id="CVModalUpload" 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">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="cvForm" name="cv" method="post" action="{{ path('student_candidate', {'id':job.id}) }}" enctype="multipart/form-data">
<div class="input-group">
<div class="custom-file">
<input type="file" name="cv[file]" class="custom-file-input" id="uploadGroup" aria-describedby="uploadButton">
<label class="custom-file-label" for="uploadGroup">Choose CV</label>
</div>
<div class="input-group-append">
<button type="submit" name="cv[send]" class="btn btn btn-primary shadow rounded-0" id="uploadButton" data-item="{{ job.id }}">Upload CV</button>
</div>
</div>
{{ form_row(form._token) }}
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The issue is because you're nesting your event handlers. To fix this move submit() outside of click().
That said, now that you've added the HTML to the question, I can see that you don't need the click handler at all. You can simply read the data-item from the button when the form is submit. Try this:
jQuery(function($) {
$("#cvForm").submit(function(e) {
e.preventDefault();
let form_data = new FormData(this); // note 'this' here
let job_id = $('#uploadButton').data('item'); // note 'data()' here
axios({
method: 'post',
url: '/job/apply/' + job_id,
data: form_data,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function(response) {
console.log(response);
}).catch(function(response) {
console.log(response);
});
});
});
Its propably because of the location where you implemented submit(). You should propably move it outside of the click()-eventHandler.
That's because you have placed your submit button inside a form. Now whenever a button is pressed inside a form, it automatically submits the form. In your case form is submitting two times, once when button is clicked and second time inside your click handler.
Easy solution to this is, just change type attribute of your submit button to "button".

How to popup(open) a bootstrap modal on ajax success

I have a JSP page,say xyz.jsp. I have a button called "send Mail" that has it's onclick() property set to a script function called sendMail(). Sending mail includes sending html data to the controller for generating PDF for which I am using Ajax. Now after the mail is sent successfully ,i want to show a pop-up indicating success. So on Ajax success i want to trigger the popup.
I am using bootstrap modal for popup.
This is my code for button and modal:
<div id="reportbuttons">
<button type="button" class="btn bg-red waves-effect" onclick="convertToPdf()" style="margin-right: 5px;float: right; margin-top: -8px">Download</button>
<button type="button" class="btn bg-red waves-effect" onclick="sendMail()" style="margin-right: 5px;float: right; margin-top: -8px">Send Mail</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-
dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data
dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
And, this is my script:
<script>
function sendMail() {
let doc = new jsPDF('p','pt','a4');
doc.setProperties({
title: 'PDF Document',
subject: 'subject',
author: 'ABC',
keywords: 'generated, javascript, web 2.0, ajax',
creator: 'XYZ'
});
//document.getElementById('reportbuttons').remove();
document.getElementById('reportbuttons').style.display ="none";
doc.addHTML(document.body, function() {
var data = doc.output('datauristring');
var reqJson = {};
reqJson.machineId = "<%=machineId%>";
reqJson.monthYear = "<%=monthYear%>";
reqJson.data = data;
$.ajax(
{
url : "sendMail/",
type: "POST",
dataType: 'json',
data : JSON.stringify(reqJson),
contentType: "application/json",
success:function(data)
{
$("#myModal").modal();
alert('mail sent successfully');
document.getElementById('reportbuttons').style.display ="block";
},
error: function(data)
{
document.getElementById('reportbuttons').style.display ="block";
}
});
});
}
</script>
I want to show the bootstrap modal popup after the mail is succesfully sent or in other words on Ajax success.

failed to load resource the server responded with a status of 403

I am trying to make two ajax calls to get amazon servers link and after that I am trying to play it in a modal but getting this I don't know how to solve or is there any other way in first ajax call I am taking the url from my own server and by that url's page I am trying to get amazon server's link after that I am trying to play a video i.e. on that link but it's not working
<script>
$(document).ready(function(){
$('.activityinstance').click(function(){
var url = $(this).find("#mod_id").attr('data-link');
$.ajax({
type : 'post' ,
url : url ,
data : {flag:'ajax'},
success: function(result){
$.ajax({
type : 'get' ,
url : result ,
success: function(data){
data=data.substring(0, data.indexOf("4"));
console.log(data);
$("#Mdlheader").html(data);
var playerInstance = jwplayer("myElement");
playerInstance.setup({
file: data,
});
}
});
}
});
});
});
</script>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 id="Mdlheader" class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div id="myElement"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

JCrop and Ajax Image upload and crop (laravel 5, Jquery)

I am currently building and image upload and crop feature on a website. the work flow is as follows
1.upload button is pressed.
2.A modal opens with an upload box
code for modal:
<div class="modal fade" 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"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Upload Profile Picture</h4>
</div>
<div class="modal-body">
<div id="load" class="display-none" style="width:32px;margin:150px auto;"><img src="img/loading2.gif"></div>
<div class="upload-container">
{!! Form::open(['file' => true, 'Method' => 'POST', 'id' => 'profile-image-upload']) !!}
<div class="alert alert-danger display-none error">
<p>File must be an image</p>
</div>
<div class="form-group">
{!! Form::label('upload', 'Upload Photo') !!}
{!! Form::file('upload', ['id' => 'file-select', 'class' => 'form-control upload-box']) !!}
</div>
{!! Form::close() !!}
</div>
<div id="image-box" class="image display-none" style="text-align:center;">
<img id="large-image" src="" style="max-width:100%;max-height:500px;display:inline-block;">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default close-button" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
click the browse button and select a photo, this instantly triggers an ajax request to upload the image and return the path to it.
server side code:
Route::post('upload-profile-pic', function(){
$input['file'] = Request::file('upload');
$rules = ['file' => 'mimes:jpg,png,gif,jpeg'];
$validator = Validator::make(
$input,
$rules
);
if ($validator->fails())
return 'false';
$identifier = str_random(20);
$image = Image::make(Request::file('upload'));
$image->encode('png')->save(public_path(). '/profile-images/temp/' . $identifier . '.png');
return $identifier;
});
On ajax success I load the resulting image into a div and show this in the modal.
Javascript (Jquery):
$('input[type=file]').change(function () {
$('#load').show();
var formData = new FormData($('#profile-image-upload')[0])
$('.upload-container').hide();
$.ajax({
type: 'POST',
url: 'upload-profile-pic',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
$('#load').hide();
console.log("success");
if (data != 'false')
console.log(data)
$("#large-image").attr('src', '/profile-images/temp/' + data + '.png');
$('.image').show();
if (data == 'false')
$('.upload-container').show();
$('.error').show();
},
error: function (data) {
$('#load').hide();
console.log("error");
console.log(data);
}
});
});
$('#myModal').on('hidden.bs.modal', function () {
$('.error').hide();
$('.upload-container').show();
$('.image').hide();
$('#profile-image-upload').trigger("reset");
})
$('.close-button').on('click', function () {
$('.error').hide();
$('.upload-container').show();
$('.image').hide();
$('#profile-image-upload').trigger("reset");
});
I also have two functions that reset the modal if it is canceled, this just hides the image and shows the upload box.
This all works as it should but my problem is that i want to apply Jcrop to the image that is generated. I have tried many things
in the ajax success funtion i added this
$("#large-image").attr('src', '/profile-images/temp/' + data + '.png').Jcrop();
The above works the first time but if the modal is closed and then the user tries again it doesn't replace the old image with the new one.
I tried adding
.done(fucntion(){
$("#large-image").Jcrop(
});
This is the same as the last option, works the first time but doesn't work after that.
I have tried
var image = $("#large-image");
then adding this to my ajax success
image.Jcrop()
and adding this to the closing functions
image.destroy()
This is the same as the last time where it wors the first time and detroy() throws an error in the console.
JavaScript isn't my strong point and i'm quite stuck on this now, can anyone help?
Resolved this using the code below:
$("#large-image").attr('src', '/profile-images/temp/' + data['identifier'] + '.png').Jcrop({}, function () {
jcrop_api = this;
$('.modal-dialog').animate({width: ($('#large-image').width() + 50)});
});
then when closing the modal i call
jcrop_api.destroy()

Twitter Bootstrap modal windows shade not closing

Hello I have Page with modal windows which I open with this JS code:
$('.open-modal').on('click', function (event) {
event.preventDefault();
var object = $(this);
modals(object.attr('href'))
})
function modals(href) {
$("#Modal").modal("hide");
$.ajax({
url: href,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'html',
//data: { id: $(this).attr('id') },
error: function (data) {
alert("wystąpił nieokreślony błąd " + data);
},
success: function (data) {
$('.modal-body').html(data);
$("#Modal").modal('show');
$('.ChangeToEdit').on('click', function (event) {
$("#Modal").modal('hide');
event.preventDefault();
var object = $(this);
modals(object.attr('href'))
})
}
});
}
and html:
<div class="modal fade" id="Modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel"></h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
and example of buttons:
<a class="open-modal" href="/User/Edit/14">Edit</a> |
<a class="open-modal" href="/User/Details/14">Details</a> |
<a class="open-modal" href="/User/Delete/14">Delete</a>
If User open modal with Details he will find modal with details and button to edit this data. After pressing that button modal window should close and open new one with edit.
Unfortunately. When user use edit button on details modal a second " shade" appears and stay there even after edit modal is closed.
What I'm doing wrong? why second shade shade from first modal doesn't disappear?
Try to do$(".modal-backdrop").removeClass(); after you closed the first modal.

Categories

Resources