I have a wizard with different forms on every step. In one of the steps I have cropper for images and on next step I want to send crop data to controller method but I can't add that to serializeArray. This is my js part:
wizard.on('beforeNext', function (wizardObj) {
wizardObj.stop();
let wizardForm = $('#kt_form_' + wizardObj.currentStep)
let dataForm = wizardForm.serializeArray()
if (wizardObj.currentStep == 2) {
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
canvas.toBlob(function (blob) {
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
var base64data = reader.result;
dataForm.push({ name: "cropImage", value: base64data });
}
});
}
let url = wizardForm.attr('action')
let method = wizardForm.attr('method')
$.ajax({
url: url,
type: method,
data: dataForm,
}).done(function (response) {
wizardObj.goNext();
})
When I console log a dataForm I see that I have cropImage attribute but on controller method it's not part of request when I dd($request->all())
Related
I'm having a problem when using the jQuery .each() and .ajax() functions together when i want to upload all input file to SharePoint document library .
function checkAttachments(NewlyCreatedItemId)
{
$("[type='file']").each(function(){
var FileUploaderID=$(this).attr("id");
var attachfor=$(this).attr("alt");
var file = document.getElementById(FileUploaderID.toString()).files[0];
if (file != undefined) {
uploadDocument(FileUploaderID,attachfor,NewlyCreatedItemId);
}
else {
alert('Please, upload attachments for ');
}
});
}
function uploadDocument(uploader,attachfor,createdID) {
var files = $("#"+uploader+"")[0].files;
if (files.length > 0) {
var fileName = files[0].name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary = "ClaimAttachments";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
// Construct the Endpoint
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?#target='" + targetUrl + "'&$expand=ListItemAllFields";
uploadFileToFolder(files[0], url, function(data) {
var file = data.d;
var DocFileName = file.Name;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
FileLeafRef: DocFileName , //FileLeafRef --> Internal Name for Name Column
AttachFor : attachfor ,
RequestGUID : createdID
};
alert("File uploaded successfully!");
}, function(data) {
alert("File uploading failed");
});
} else {
alert("Kindly select a file to upload.!");
}
}
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileObj);
// Add the file to the SharePoint folder.
getFile.done(function(arrayBuffer) {
$.ajax({
url: apiUrl,//File Collection Endpoint
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function(data) {
success(data);
},
error: function(data) {
success(data);
}
});
});
}
it uploads the file of the first file uploader only because when it reach to the ajax call in function (uploadFileToFolder) go to the next iteration, how to can solve it .
I am having an issue with my file upload from javascript to laravel and displaying it for later use, below is my code to upload and save to db and retrieve later and display it
$(document).on("change", "#facesheet", function() {
handleFileSelect($(this));
});
function handleFileSelect(evt) {
var files = $(evt)[0].files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var fileString = e.target.result;
$("#divFileUpload").removeData("file");
$("#divFileUpload").removeData(
"filename");
$("#divFileUpload").removeData("extension");
$("#divFileUpload").data("file", fileString);
$("#divFileUpload").data(
"filename", theFile.name);
$("#divFileUpload").data("extension", theFile
.name.split('.').pop().toLowerCase());
};
})(f);
reader.readAsDataURL(f);
}
}
on submit button in modal, this code will execute and saves to db using base64_encode object and stores as blob
function uploadpdf() {
var $formdata = {
'data': $("#divFileUpload").data("file"),
'filename': $("#divFileUpload").data("filename"),
'type': $("#divFileUpload").data("extension"),
'Number': $("#hdnNumber").val()
};
$.ajax({
url: '/upload',
type: 'POST',
data: $formdata,
success: function(response) {
alert("Uploaded successfully");
window.location.reload();
}
});
return false;
}
when a user click on the uploaded file it opens a new window to display the file. Everything works fine with this as long as pdf contains text data but when pdf is completely an image then it wont display anything, any help will be appreciated on this.
I am creating the function to save data using javascript pass to backend. Now I need to combine two function with 1 function in the javascript. Because I want to click one button can run the two functions.
First function - The first function is once I've clicked the button, the images will show in the page then pass to backend to do the save function.
function save_qr(form) {
html2canvas($("#createImg"), {
onrendered: function(canvas) {
var imgsrc = canvas.toDataURL("image/png");
console.log(imgsrc);
$("#newimg").attr('src', imgsrc);
$("#img").show();
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "?f=" + loc,
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}
});
}
Second function- This function will pass to backend to do insert form data function.
function save_qr(form) {
var error_msg = new Array();
$("#" + form + " .blank").each(function() {
if ($.trim($(this).val()) == "") {
error_msg.push("The " + $(this).attr("title") + " should not be blank.");
}
});
var loc = getQueryVariable('loc');
var serialized = $('#' + form).serialize();
var extra = '&action=save';
var form_data = serialized + extra;
if (error_msg.length < 1) {
$.ajax({
type: 'POST',
url: "?f=" + loc,
data: form_data,
beforeSend: function() {
show_overLay();
},
success: function(data) {
if (data) {
console.log(data);
hide_overLay(data);
//$('#save').prop('disabled',true);
window.location = "?loc=" + loc;
} else {
hide_overLay(data);
}
}
});
} else {
alert(error_msg.join("\n"));
}
}
That means I want to do the first function first to show the image first then to do the second function. The url using same location backend within in the two functions. Hope someone can guide me how to combine these two function with 1 function. Thanks.
Noteļ¼These two functions are worked if do it separate.
ERROR:
Am I just blind or is it that simply. Rename the functions to save_qr1 and save_qr2 (Currently the functions have the same name) and use them in a new full_save_qr function:
function full_save_qr(form) {
save_qr1(form);
save_qr2(form);
}
The functions are processes synchronous. That means your save_qr1 will be processed before save_qr2. If you want a specific time to happen between the two functions you need to use something like setTimeout
function full_save_qr(form) {
save_qr1(form);
setTimeout(() => save_qr2(form), 1000);
}
Simply add global variable like var isImageShow = false. Call wrap your code like
var isImageShow = false;
function save_qr(form) {
if (!isImageShow) {
isImageShow = true;
// 1st function code
} else {
// 2nd function code
}
}
If you want to check condition on dataURL then declare dataURL as global variable. And update condition as if(!dataURL). Also update var dataURL = canvas.toDataURL(); to dataURL = canvas.toDataURL(); so it will use globally declared dataURL.
var dataURL = "";
function save_qr(form) {
if (!dataURL) {
html2canvas($("#createImg"), {
onrendered: function(canvas) {
var imgsrc = canvas.toDataURL("image/png");
console.log(imgsrc);
$("#newimg").attr('src', imgsrc);
$("#img").show();
dataURL = canvas.toDataURL(); // removed var from here.
$.ajax({
type: "POST",
url: "?f=" + loc,
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}
});
} else {
// 2nd function code
}
}
I am trying to convert .HEIC image to .JPG using libheif.
libheif converts image on client side browser window only. So in order to save the image i converted image to base64 and then performed ajax to save the image using file_put_contents.
this.canvas.toBlob(function(blob) {
var extension = FILE_EXTENSIONS[blob.type] || ".bin";
var basename = this.filename.replace(/\.[^/.]+$/, "");
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, basename + extension);
return;
}
var readers = new FileReader();
var base64image;
readers.readAsDataURL(blob);
readers.onload = function () {
var base64image = readers.result; // data <-- in this var you have the file data in Base64 format
// console.log(base64image);
// call ajax
var formData = new FormData();
formData.append('filename', basename);
formData.append('avatar', readers.result);
$.ajax('upload.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function () {
}
});
};
return;
// this.downloads.appendChild(dlink);
// dlink.click();
// URL.revokeObjectURL(url);
}.bind(this), format);
When i convert a single image then it works fine. But if i try to convert in loop it does not works.
Before completing js conversion, my php loop runs (I think this is the issue) So i tried php function sleep() and js set timeout(), But unfortunately none worked.
(function() {
var demo = new HeifDemo(libheif);
<?php $img_array = array('demo/1.heic', 'demo/2.heic', 'demo/3.heic');
foreach ($img_array as $img) : ?>
function saveImage(subject, callback) {
demo.loadUrl(subject);
callback();
}
saveImage('<?php echo $img; ?>', function() {
// demo.saveImage();
setTimeout( function(){
demo.saveImage();
}, 2500 );
});
//});
<?php sleep(4); endforeach; ?> }).call();
I am trying to save image file through signature pad. I want the name of the file to be an element from my div. Which changes accordingly. Here is my code. It is saving the image but the filename is blank(.png).
Javascript:
$("#btnSaveSign").click(function(e){
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
var p = document.getElementById('my_class').innerHtml;
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:p}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
save_sign.php:
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = $_POST['p'];
//Location to where you want to created sign image
$file_name = './doc_signs/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
?>
Replace with your assignment with var p = document.getElementById('my_class').value;
Due to onrendered function is a callback, it may not get the document.getElementById('my_class').innerHtml properly. Please get echo out the $_POST['p'] to make sure proper filename is sent to PHP side.
get document.getElementById('my_class').innerHtml before call html2canvas function.
$("#btnSaveSign").click(function(e){
var p = document.getElementById('my_class').innerText;
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
// ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:p}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
$("#btnSaveSign").click(function(e){
var p = document.getElementById('my_class').innerText;
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
// ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:document.getElementById('my_class').innerText}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});