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

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()

Related

Laravel How to reset modal ajax data values upon closing the modal

I am currently working on populating a user's searching for available appointments by selecting a date, start time and end time. I am trying to populate them onto a modal which is currently working. However I realise that whenever I close the modal and search for the new timeslots, the previous data populated on the modal will still be there.
I have tried doing function when I close the modal, the modal data will be cleared.
Below are my html codes for the modal:
<div class="modal fade" id="myModalNewAppointment">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Select Appointment</h4>
</div>
<!-- Modal body -->
<div class="modal-body">
{{-- <form id="test" action="" method="post"> --}}
<div class="form-group">
<label for="modal">Select a Timeslot</label>
<div class="spacer"></div>
<div class="timeslots-section">
<div class="timeslots text-center">
</div> <!-- end timeslots -->
</div>
</div>
{{-- </form> --}}
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="new_appt_cfm_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Confirm</button>
<button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Below is my ajax method to retrieve the timeslots:
$("#find_appointment_btn").click(function(event){
event.preventDefault();
let select_date = $('#select_date').val();
let start_time = $('#start_time').val();
let end_time = $('#end_time').val();
let data = { select_date: select_date, start_time: start_time, end_time: end_time };
$.ajax({
type:"POST",
url: "{{ route('assistant.newappts.get') }}",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
dataType: "json",
success:function(data){
console.log(data);
if(data == ""){
alert("Clinic is close!");
return;
}
else if(data != ""){
$('#myModalNewAppointment').modal({backdrop: 'static', keyboard: false});
data.forEach(function(dt) {
// do something with `item`
// $(".timeslots").append(dt);
$('.timeslots').append('<input type="checkbox" class="timeslotchk" name="timeslot" value="'+ dt +'"/>' + dt );
});
}
},
error: function(error) {
console.log(error);
}
});
});
Below is the method I have tried to reset the data populated on my modal:
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').reset();
});
When you call the ajax request on the success you have appended the data in model "timeslots" division so its obvious that data will be still there on the hiding model try to empty the timeslots, try below code hope it work for you and make sure that method trigger on closing of model
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').find(".timeslots").empty();
});

AJAX call not triggered on show.bs.modal

I have a button which is supposed to trigger a modal with a contact form. Part of the show.bs.modal function is an AJAX call to my DB to get some file details which are then meant to be shown in the modal-body.
The problem is that the modal does indeed open, but with no modal-body content, which means that the JavaScript code to trigger to the AJAX call is not working. I do not see any network activity in the browser debug menu, no call to the PHP file, and even an alert on top of the JS code telling me that that a button was pressed is not triggered. It seems like the whole JS code is circumvented, yet the modal still shows.
The same code works in another project, anyone has any idea as to why this is happening?
Button:
<div class="card-footer bg-light text-center">
<button id="modal_btn" name="modal_btn" type="button" class="btn bg-teal-400" data-toggle="modal" data-target="#modal_contact_form" data-imgid="'.$row['image_id'].'" data-keyboard="true">
<span class="icon-ico-mail4"></span> Anfragen
</button>
</div>
Modal:
<!-- Contact form modal -->
<div id="modal_contact_form" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-teal-300">
<h3 class="modal-title">Kaufanfrage - Artikel #1234</h3>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn bg-teal-300">Nachricht Senden</button>
</div>
</form>
</div>
</div>
</div>
<!-- /contact form modal -->
JavaScript:
<script type="text/javascript">
// DISPLAY EDIT RECORD MODAL
$('#modal_contact_form').on('show.bs.modal', function (event) {
//var button = $(event.relatedTarget) // Button that triggered the modal
window.alert("button clicked.");
var imgid = $(event.relatedTarget).data('imgid') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'action=contact&imgid=' + imgid;
$.ajax({
type: "POST",
url: "./assets/ajax/ajax_action.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
}
});
});
</script>
try this:
$(document).on('show.bs.modal','#modal_contact_form', function (event) {
// TODO ....
});
Or you can use the onclick button trigger instead of modal show trigger
$("#modal_btn").click(function(event){
// TODO ...
});
Try This
const bsModal = document.querySelector('#exampleModal');
$(bsModal).on('shown.bs.modal', function() {
// YOUR CODE HERE....
})

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.

CKEditor is not working with bootstrap modal

I want to show ckEditor on bootstrap modal but the ckEditor is not opening as shown below. After searching through the internet I have got some solution in a different way like this link but I will perform an ajax request hence I have to open the modal using $('.cia_modal').modal('toggle'). The above-mentioned solution link does not work for me
Modal Button:
<button class="btn btn-info btn-xs cia_modal_btn" data-id="<?php echo $post->post_id; ?>" data-table="post" data-attr="post_id">
Create New Post
</button>
Modal:
<!--Modal-->
<div class="modal fade cia_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">Create New Post</h4>
</div>
<div class="modal-body">
<form action="/action_page.php">
<div class="form-group">
<textarea class="ck_editor" name="post" id="" cols="30" rows="10"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--End Modal-->
Javascript:
<script type="text/javascript">
$(document).on("click", ".modal_btn", function (e) {
e.preventDefault();
e.stopPropagation();
let cia_modal = $('.cia_modal');
//Set modal show/hide
cia_modal.modal('toggle');
let id = $(this).attr('data-id');
let table = $(this).attr('data-table');
let attr = $(this).attr('data-attr');
//Set Form Data
let formData = new FormData();
formData.append('id',id);
formData.append('table',table);
formData.append('attr',attr);
$.ajax({
type: 'post',
url: '<?php echo base_url()?>post/create_post',
data: formData,
contentType: false,
processData: false,
success: function (data) {
//
}
});
});
</script>
Please help me. Thanks
I assume, you are using CKEditor 4.x.
You need to create editor using CKEDITOR.replace( 'ck_editor' ), you can do it only on element that is existing inside document. It doesn't matter if it's hidden or not. If your modal is inside DOM, but hidden, then just initialize editor. Otherwise you need to wait until element is appended then call CKEDITOR.replace.
Depending on how bootstraps implements modal.show. If it's just changes CSS to make it visible, then most likely you can initialize editor at the start of your script, if it adds elements to document, then you need to use some of bootstrap events to create editor in right time. See shown.bs.modal: https://getbootstrap.com/docs/4.0/components/modal/#events
Just initialize the editor:
<script type="text/javascript">
ClassicEditor.create($('.ck_editor')[0])
.then( editor => {
console.log( editor );
})
.catch( error => {
console.log( error );
});
$(document).on("click", ".modal_btn", function (e) {
//....

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

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',
...

Categories

Resources