Ajax method working twice in a button click - javascript

The file upload function working on the Upload button click.The function
$("#fuPDFAdd").change(function () {})
file upload change is working two time when click the 'btnUploadAdd' button.
How can avoid this
<div id="divUploadFileAdd">
<form enctype="multipart/form-data" id="frmUplaodFileAdd">
#Html.AntiForgeryToken()
<input id="fuPDFAdd" name="file" type="file" style = "display:none;"/>
<button class="" id="btnUploadAdd" type="button" onclick="test()">Upload</button>
<label id="txtuploadedMsgAdd"> </label>
</form>
</div>
$(document).ready(function () {
$("#fuPDFAdd").change(function () {
console.log("tst1");
var file = this.files[0];
fileName = file.name;
size = file.size;
type = file.type;
if (type.toLowerCase() == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { //I just want pdf files and only want to show
var formData = new FormData($('#frmUplaodFileAdd')[0]);
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) {
grdStaffAddition.PerformCallback({ transStatus: "New" });
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'success', 'Template migration completed' + data.result, 'CAM - Contract Staff');
}
});
}
else {
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'error', 'Please select xls/xlsx file.', 'CAM - Contract Staff');
}
});
});
function test() {
$("#fuPDFAdd").click();
}

Something like this will work, I did wrap the file upload code to a separate function there, and make it to call this new function from your event listeners.
function uploadTheFile() {
console.log("tst1");
var file = this.files[0];
fileName = file.name;
size = file.size;
type = file.type;
if (type.toLowerCase() == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { //I just want pdf files and only want to show
var formData = new FormData($('#frmUplaodFileAdd')[0]);
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function(data) {
grdStaffAddition.PerformCallback({
transStatus: "New"
});
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'success', 'Template migration completed' + data.result, 'CAM - Contract Staff');
}
});
} else {
ShowClientToastr('False', 'False', 'toast-bottom-right', 'True', 'error', 'Please select xls/xlsx file.', 'CAM - Contract Staff');
}
}
$("#fuPDFAdd").change(function() {
uploadTheFile();
});
function test() {
uploadTheFile();
}

Related

I need to validate the form, the ajax should only work if the form validates

I'm trying to validate the form. Its validating perfectly but the form is not submitting. In the console it says isValid() is not a function
I tried to give a condition that form validates
$('#saveStudent').parsley();
var addvalidation = new JustValidate('#saveStudent');
addvalidation.addField('#poster', [{
rule: 'files',
value: {
files: {
extensions: ['jpeg', 'png', 'jpg'],
// maxSize: 25000,
// minSize: 1000,
types: ['image/jpeg', 'image/png', 'image/jpg'],
// names: ['file1.jpeg', 'file2.png'],
},
},
errorMessage: 'Only jpeg, jpg, png formats are supported.',
}, ]);
$(document).on('submit', '#saveStudent', function (e) {
e.preventDefault();
var formData = new FormData(this);
formData.append("save_student", true);
if ($(this).parsley().isValid() && addvalidation.isValid()) {
$.ajax({
type: "POST",
url: "save.php",
data: formData,
processData: false,
contentType: false,
success: function (response) {
$('#addMovie').show();
$('#studentAddModal').modal('hide');
$('#saveStudent')[0].`your text`reset();
$('#myTable').load(location.href + " #myTable");
}
});
}
});

Multiple File Upload using dropzone and with other forms fields with FormValidation plugin

This is the image of form which I have designed in my project Now my requirement is to upload multiple files and with other form values over a single backend call.
<script>
<form class="form-horizontal" name="addColorForm" id="addColorForm"
enctype="multipart/form-data"
method="POST">
//Colour Name and Code fileds
//Files Uploader Plugin (Dropzone)
<input type="file" name="artworkFiles[]" style="visibility: hidden"/>
</form>
Now my script part
<script>
var validCode = function () { // my custom validation };
FormValidation.validators.validCode = validCode;
FormValidation.formValidation(
document.getElementById('addColorForm'),
{
fields: {
colorName: {
validators: {
notEmpty: {
message: '${message(code:"blank.error.message", default:"This field must be entered")}'
},
}
},
},
plugins: { //Learn more: https://formvalidation.io/guide/plugins
trigger: new FormValidation.plugins.Trigger(),
// Bootstrap Framework Integration
bootstrap: new FormValidation.plugins.Bootstrap(),
// Validate fields when clicking the Submit button
submitButton: new FormValidation.plugins.SubmitButton(),
// Submit the form when all fields are valid
// defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
}
}
).on('core.form.valid', function () {
saveColor();
});
function saveColor() {
var url = "url";
var form = $("#createArtworkForm");
var formData = new FormData(form[0]);
$.ajax({
url: url,
type: 'POST',
enctype: 'multipart/form-data',
data: formData,
success: function (data) {},
cache: false,
contentType: false,
processData: false,
error: function () { }
});
}
var artworkColorsFiles = $('#kt_dropzone').dropzone({
url: "https://www.google.com", // Set the url for your upload script location
paramName: "media", // The name that will be used to transfer the file
maxFiles: 1,
maxFilesize: 40, // MB
addRemoveLinks: true,
acceptedFiles: "image/*",
autoProcessQueue: false,
accept: function (file) {
//Logic to add multiple files in an input type hidden which is declared above
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function () {
let content = fileReader.result;
$('#artworkFiles').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
});
</script>
My questions is how to implement this or how should i add my all files(max 3) in a input type file field declared as visibility hidden.
The same I did in my project here is the code hope it will help you.
you have to use the dropzone function to send file and form data in sendingmultiple function you have to add a loop through your formdata enter code here
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
$(document).ready(function () {
zdrop = new Dropzone('#dropzone', {
url: '#Url.Action("SaveOpportunity", "Masters")',
maxFiles: 500,
maxFilesize: 300,
parallelUploads: 100,
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple: true,
removeFilePromise: function () {
return new Promise((resolve, reject) => {
let rand = Math.floor(Math.random() * 3)
console.log(rand);
if (rand == 0) reject('didnt remove properly');
if (rand > 0) resolve();
});
},
sendingmultiple: function (file, xhr, formData) {
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
debugger
$("form#OpportunityForm").find("input[type=file]").each(function (index, field) {
const file = field.files[0];
formData.append('itemfile', file);
});
},
successmultiple: function (file, responseText) {
jQuery('form#OpportunityForm').find('textarea, input').each(function () {
jQuery(this).val('');
});
clear();
swal.fire("Opportunity Details Saved!", "Opportunity details Saved Successfully!", "success");
OpportunityMstList();
GetOpportunityMstList();
location.reload();
$("#myModal").modal('hide');
},
});
after adding this on the form submit button click you have to add this for creating blob file when you post data without image file.
jQuery(document).on('click', 'button#saveOpportunity', function (e) {
e.preventDefault();
if ($("#OpportunityForm").validate().form()) {
if (zdrop.files.length == 0) {
var blob = new Blob();
blob.upload = { 'chunked': zdrop.defaultOptions.chunking };
zdrop.uploadFile(blob); // just submit the form
} else if (zdrop.getRejectedFiles().length > 0) {
alert("The attached file is invalid");
} else {
zdrop.processQueue();
}
}
});

"Load-Image" Javascript resize image before upload

I'm developing a small function for an image-upload. This image-upload resizes selected pictures on the client and upload the resized image.
This works, but the browser will hang a lot between "resizes-functionality".
This is my code:
function manageImage(file) {
if (!file) return;
var mime = file.type;
var src = URL.createObjectURL(file);
loadImage.parseMetaData(file, function (data) {
var options = { maxWidth: 1920, maxHeight: 1920, canvas: true };
if (data.exif) {
options.orientation = data.exif.get('Orientation');
}
loadImage(file,
function (img, test) {
loaded++;
var formData = new FormData();
formData.append("image", dataURI);
$.ajax({
url: "/URL",
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
type: "POST",
success: function (resp) {
}
}).error(function () {
}).done(function () {
if (loaded < checkedFiles.length) {
manageImage(files[loaded]);
} else {
//FINISHED
}
});
},
options);
});
}
manageImage(files[0]);
This funcition is recursive, because i had some problems with the iteration (browser-hang, memory and cpu-usage).
Additionally, i'm using this library for EXIF-Data and correct orientation on mobile phones:
https://github.com/blueimp/JavaScript-Load-Image
With one or two selected pictures (e.g. 7MB) it works perfect, but i want to upload maybe 50 pictures.
It would be great if someone can give me a clue?!

Send Cropped image to database ajax On client and PHP on server

I am trying to upload a image to Database using Javascript on client and PHP on server.
first image is selected from the gallery.
after zooming and cropping the image is passed to database
The Problem is when iam trying to submit the cropped image value is not passed to the php the actual uploaded input "File" Value is Being Passed, but i need the cropped areas value to be passed to PHP.
For testing purpose if all the js are required i can provide it.
Js: This Crops the image
$(function() {
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 40,
});
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
window.open(imageData);
});
});
HTML:
<form id="uploadForm" class="image-editor">
<input type="file" class="cropit-image-input">
<!-- .cropit-image-preview-container is needed for background image to work -->
<div class="cropit-image-preview-container">
<div class="cropit-image-preview"></div>
</div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<input type="submit" class="export">Export</input >
</form>
Ajax: ajax sends the data to php
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});
});
PHP:
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$mysl = mysqli_connect("localhost", "root", "root","test");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "UPDATE output_images SET imageType ='{$imageProperties['mime']}',imageData= '{$imgData}' WHERE imageId='16'";
$current_id = mysqli_query($mysl,
$sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error());;
if(isset($current_id)) {
echo "done";
}
}
}
First, take a look at this: Can I pass image form data to a PHP function for upload?
I think the issue is here: var imageData = $('.image-editor').cropit('export');. Since this new image is never a part of the form, there is no way to pass it via AJAX.
In your JS/JQuery, I would advise:
var imageData = '';
$(function() {
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 40,
});
$('.export').click(function() {
imageData = $('.image-editor').cropit('export');
window.open(imageData);
});
});
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
var fd = new FormData(this);
fd.append( imageData, file );
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});
});
EDIT
In your example, you never defined a name or id attribute for your input, so there would be no way for PHP to index the $_FILES global. Could try $_FILES[0]. I would advise assigning that in your form or when you post it.
You can adjust the myFormData.append(name, file, filename);. So it would be:
fd.append('crop-image', imageData, 'crop-image.jpg');
Then in PHP, you call it using $_FILES['crop-image']. If you want to pass the file name from the form:
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
var fd = new FormData(this);
var origFileName = $("input[type='file']").val();
var startIndex = (origFileName.indexOf('\\') >= 0 ? origFileName.lastIndexOf('\\') : origFileName.lastIndexOf('/'));
var filename = origFileName.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0){
filename = filename.substring(1);
}
var cropFileName = "crop-" + filename;
fd.append('crop-image' imageData, cropFileName );
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});

Track ajax post progress for fileupload using jquery ajax and FormData

var files = [];
$(document).ready(function (){
dropArea = document.getElementById("droparea");
});
// when we drag and drop files into the div#droparea
dropArea.addEventListener("drop", function (evt) {
files = evt.dataTransfer.files;
}, false);
function uploadFiles(stepX) {
var url = "/ajax/uploadfiles.php";
var type = "POST";
if (files.length > 0) {
var data = new FormData(); // we use FormData here to send the multiple files data for upload
for (var i=0; i<files.length; i++) {
var file = files[i];
data.append(i, file);
}
//start the ajax
return $.ajax({
//this is the php file that processes the data and send mail
url: url,
//POST method is used
type: type,
//pass the data
data: data,
//Do not cache the page
cache: false,
// DO NOT set the contentType and processData
// see http://stackoverflow.com/a/5976031/80353
contentType: false,
processData: false,
//success
success: function (json) {
//if POST is a success expect no errors
if (json.error == null && json.result != null) {
data = json.result.data;
// error
} else {
alert(json.error);
}
}
});
}
return {'error' : 'No files', 'result' : null};
}
How do I track the progress of the file upload if I want to retain this method to upload files to server?
Note the comment with #TODO
//start the ajax
return $.ajax({
//this is the php file that processes the data and send mail
url: url,
//POST method is used
type: type,
//pass the data
data: data,
//Do not cache the page
cache: false,
//#TODO start here
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//#TODO end here
// DO NOT set the contentType and processData
// see http://stackoverflow.com/a/5976031/80353
contentType: false,
processData: false,
Add a standalone function that updates the progress.
function updateProgress(evt) {
console.log('updateProgress');
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
} else {
// Unable to compute progress information since the total size is unknown
console.log('unable to complete');
}
}
From https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest > Monitoring progress

Categories