Uploading One File Through AJAX Sending Empty String - javascript

I'm sending one file to a PHP file through an AJAX POST request but it's sending an empty string even though if I tried to send the name only or size etc. it works just fine.
Am I doing something wrong here?
$(document).ready(function() {
let validExt = ['jpg', 'jpeg', 'png']
$('#file-upload').change(function() {
var extension = this.files[0].type.split('/')[1]
if (validExt.indexOf(extension) == -1) {
swal({
title: "!الملف غير صالح " + "(" + this.files[0].type.split('/')[1] + ")",
text: "('jpg' , 'jpeg' , 'png') الصيغ المقبولة",
icon: "warning",
button: "رجوع",
});
return false;
} else if (this.files[0].size > 2000000) {
swal({
title: "!الملف غير صالح" + "(" + (this.files[0].size / 1024 / 1024)
.toFixed(2) + "MB)",
text: "لا يمكن ان يزيد حجم الملف عن 2 ميغابايت",
icon: "warning",
button: "رجوع",
});
return false;
}
var file_data = $('#file-upload').prop('files');
var form_data = new FormData();
form_data.append('files', file_data);
$.ajax({
url: "edit-product.php",
type: "POST",
data: file_data,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log(form_data);
// $(document).ready(function(e) {
// setTimeout(function() {
// location.reload();
// }, 2000)
// });
}
});
});
});
<input accept=".png,.jpg,.jpeg" type="file" class="form-control-file d-none" id="file-upload" name="file-upload">

Related

File upload progress Custom page RestAPI SPO

The code below is working fine to upload files to SPO through RestAPI. No feedback is received on file upload progress. An alert is thrown once the upload is complete.
I would like to have a progress bar to display the upload percentage and reload this upload page while clicking OK to the successful alert message.
Kindly assist.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function () {
init();
});
function init(){
$("#btnUploadFiles").click(function(){
var files=$("#inputTypeFiles")[0].files;
uploadFiles(files[0]); // uploading singe file
});
}
function uploadFiles (uploadFileObj) {
var fileName = uploadFileObj.name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary="TEST";
var folderName = "";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/" + folderName;
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?$expand=ListItemAllFields&#target='" + targetUrl + "'";
uploadFileToFolder(uploadFileObj, url, function (data) {
var file = data.d;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
departname: $("#departname").val(), //meta data column1
Filename: $("#filename").val(), //meta data column2
ACFTREG: $("#ACFTREG").val(), //meta data column3
Date: $("#datepicker").val() //meta data column4
};
url = webUrl + "/_api/Web/lists/getbytitle('"+documentLibrary+"')/items(" + file.ListItemAllFields.Id + ")";
updateFileMetadata(url, updateObject, file, function (data) {
alert("File uploaded & metadata updation done successfully");
}, function (data) {
alert("File upload done but metadata updating FAILED");
});
}, function (data) {
alert("File uploading and metadata updating FAILED");
});
}
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;
var getFile = getFileBuffer(fileObj);
getFile.done(function (arrayBuffer) {
$.ajax({
url: apiUrl,
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) {
failure(data);
}
});
});
}
function updateFileMetadata(apiUrl, updateObject, file, success, failure) {
$.ajax({
url: apiUrl,
type: "POST",
async: false,
data: JSON.stringify(updateObject),
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Content-Type": "application/json;odata=verbose",
"X-Http-Method": "MERGE",
"IF-MATCH": file.ListItemAllFields.__metadata.etag,
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItems);
function getItems() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('L%20-%20MDB%20-%20ACFTREG')/items?$Select=Title&$top=2000",
type: "GET",
headers: {
"accept": "application / json;odata = verbose",
},
success: function(data) {
var results = data.d.results;
var options = "";
for(var i = 0; i < results.length; i++){
options = options + "<option value='" + results[i].Title + "'>" + results[i].Title + "</option>";
}
$("#ACFTREG").append(options);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
$( function() {$( "#datepicker" ).datepicker(
{
changeMonth: true,
changeYear: true
}
);} );
</script>
Select File:<input type="File" id="inputTypeFiles" /><br />
Departname: <input id="departname" type="textbox"/><br />
Date: <input type="text" id="datepicker" autocomplete="off" name="hidden"><br />
Filename: <input id="filename" type="textbox"/><br />
ACFTREG: <select id="ACFTREG" class="select">
<option selected="selected">Select</option><br />
<input type="button" id="btnUploadFiles" value="Upload"/><br />
Inside the $.ajax({}) function, you can add the xhr setting inside the ajax.
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
// Place upload progress bar visibility code here
}
}, false);
return xhr;
},
type: 'POST',
//add the rest of ajax settings
check this link for ajax documentation
jQuery/ajax
check this link for example on upload progress
jQuery-upload-progress/example

Redirect whit SweetAlert2

i have a problem with redirect page after the user click on ok button in sweet alert. i don't understand where i have to insert the code and which code. i would like that when the user press ok, after the success on form, is redirected to... example "google.com".
I tried to use the solutions on the site, but they did not work or I was wrong to insert them
Thanks to all for help
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9"></script>
<script>
$(function() {
$(document).ajaxStop($.unblockUI);
$('form').on('submit', function(e) {
e.preventDefault();
var response = grecaptcha.getResponse();
if(response.length == 0) {
//reCaptcha not verified
alert("Verifica di non essere un robot!");
return false;
} else {
//reCaptch verified
$.blockUI({
message: '<p><img src="img/Eclipse-1s-134px.svg" alt="">Ci siamo...non uscire</p>'
});
var formData = new FormData(this);
$.ajax({
type: 'post',
url: 'mailer.php',
data: formData,
cache: false,
dataType: 'json',
contentType: false,
processData: false,
mimeType: "multipart/form-data",
xhr: function () {
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
$('.progress-bar').animate({
width: percent + '%'
}, {
duration: 100
});
}, true);
}
return xhr;
},
success: function (response) {
if (response.success) {
Swal.fire(
'Perfetto!',
'Il tuo locale è registrato!',
'success'
);
$('form').trigger("reset");
$('.progress-bar').animate({
width: '10%'
}, {
duration: 1000
});
} else {
alert(response.message);
}
},
error: function (response) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Qualcosa è andato storto!',
footer: '<a href>Riprovaci!</a>'
});
}
});
}
});
});
</script>
I think it must be placed before the success code, something like this:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9"></script>
<script>
$(function() {
$(document).ajaxStop($.unblockUI);
$('form').on('submit', function(e) {
e.preventDefault();
var response = grecaptcha.getResponse();
if(response.length == 0) {
//reCaptcha not verified
alert("Verifica di non essere un robot!");
return false;
} else {
//reCaptch verified
$.blockUI({
message: '<p><img src="img/Eclipse-1s-134px.svg" alt="">Ci siamo...non uscire</p>'
});
var formData = new FormData(this);
$.ajax({
type: 'post',
url: 'mailer.php',
data: formData,
cache: false,
dataType: 'json',
contentType: false,
processData: false,
mimeType: "multipart/form-data",
xhr: function () {
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
$('.progress-bar').animate({
width: percent + '%'
}, {
duration: 100
});
}, true);
}
return xhr;
},
success: function (response) {
if (response.success) {
Swal.fire(
'Perfetto!',
'Il tuo locale è registrato!',
'success'
);
$('form').trigger("reset");
$('.progress-bar').animate({
width: '10%'
}, {
duration: 1000
});
window.location.href = 'www.yourpage.com';
} else {
alert(response.message);
}
},
error: function (response) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Qualcosa è andato storto!',
footer: '<a href>Riprovaci!</a>'
});
}
});
}
});
});
</script>

How to get the file uploading progress status in ajax call?

I am uploading the multiple files through ajax, where i need to keep a progress bar. I am able to get the progress complete status only after all the process done, so i need to keep the progress bar showing status during upload.
Here when I clicking the 'btnEditImageSave' button, I am checking whether the existing file is getting delete and uploading in if condition.
In that storing the uploading file and passing it for uploading process in ajax complete function. In it that i have included the progress bar code to show the progress status, but its showing only after the all the process completes.
$('#btnEditImageSave').unbind().click(function (event) {
$('#progressBardiv').css('width', '0');
$('.progressBardiv').text('');
if (uploadedfiles.length > 0 && deleteFiles.length == 0) {
if (editStoredFiles.length > 0) {
var files = new FormData();
for (var i = 0; i < editStoredFiles.length; i++) {
if (editStoredFiles[i].size > 0) {
files.append(editStoredFiles[i].name, editStoredFiles[i]);
}
}
uploadedfiles = [];
files.append('SerialNumber', editSerialNumber);
$.ajax({
type: "POST",
url: productionBaseUrl + '/Home/UploadDockingStationFiles',
data: files,
contentType: false,
processData: false,
async: true,
complete: function () {
uploadedfiles = [];
$('#editfileupload').val();
$.ajax({
type: "POST",
url: cloudServerUrl + "/api/dockstation/updatefiledisplaytimer",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
SerialNumber: $('#ddlEditDockingStationSerialNumber').val(),
FileSpinTimer: $('#txtEditTimer').val(),
IsHDMIUpdate: isHDMIUpdate
}),
/*----My Progress Bar code----*/
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (event) {
if (event.lengthComputable) {
var percentComplete = event.loaded / event.total;
percentComplete = parseInt(percentComplete * 100);
$('#progressBardiv').text(percentComplete + '%');
$('#progressBardiv').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
complete: function () {
$('#loading-popup').hide();
$('#divEditDockingStationImages').dialog("close");
$.popup('<pre>Message</pre>', "Image Configuration Updated Successfully.", 'OK');
return false;
}
});
}
});
}
}
else {
$('#loading-popup').hide();
$.popup('<pre>Message</pre>', "Please Select a File.", 'OK');
return false;
}
}
<div class="progress">
<div id="progressBardiv" class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="">
<span class="sr-only"></span>
</div>
</div>
For those in 2022 still looking how to measure an XHR upload operation progress, there's an API called ProgressEvent (https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent) with broad support of major browsers. No need to use custom plugins.
Also, a detailed post with examples on how to use this can be found here: https://medium.com/swlh/uploading-files-with-progress-monitoring-in-vanillajs-angular-and-vuejs-625e2491821
You can use plUpload plugin to upload files..
Follow this link:https://www.plupload.com/docs
it has its own event for progressbar...
See the sample code below...
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles', // you can pass in id...
container: document.getElementById('container'), // ... or DOM Element itself
url: "//",
filters: {
max_file_size: '500mb',
mime_types: [
{ title: "PDF files", extensions: "pdf" }
]
},
flash_swf_url: '/plupload/js/Moxie.swf', // Flash settings
silverlight_xap_url: '/plupload/js/Moxie.xap', // Silverlight settings
init: {
PostInit: function () {
// whereas filelist is the divid which contains uploaded file names....
document.getElementById('filelist').innerHTML = '';
uploader.start();
},
FilesAdded: function (up, files) {
plupload.each(files, function (file) {
document.getElementById('filelist').innerHTML +=
'<div id ="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) +
') <b></b> Remove</div>' +
'<div class="progressbar" id ="progressBar_' + file.id + '"> <div class="mybar" id="myBar' + file.id + '"></div></div>';
});
},
UploadProgress: function (up, file) {
var $progressId = $("#filelist div#progressBar_" + file.id + " div.mybar");
$progressId.css('width', file.percent + '%');
//To Remove 'Remove Link' while file is in uploading state.
$("#filelist div#" + file.id).find('a.remove').remove();
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
FileUploaded: function (up, file, ServerResponse) {
var response = JSON.parse(ServerResponse.response);
},
UploadComplete: function (up, file) {
},
Error: function (up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
}
}
});
uploader.init();
I have used in my project have a look on snapshot below,
if (deleteFiles.length > 0 && uploadedfiles.length > 0) {
$.ajax({
type: "POST",
url: productionBaseUrl + "/Home/DeleteDockingStationFiles",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: JSON.stringify({
serialNumber: editSerialNumber,
files: deleteFiles
}),
complete: function () {
deleteFiles = [];
if (editStoredFiles.length > 0) {
var files = new FormData();
for (var i = 0; i < editStoredFiles.length; i++) {
if (editStoredFiles[i].size > 0) {
files.append(editStoredFiles[i].name, editStoredFiles[i]);
}
}
uploadedfiles = [];
files.append('SerialNumber', editSerialNumber);
$.ajax({
type: "POST",
url: productionBaseUrl + '/Home/UploadDockingStationFiles',
data: files,
contentType: false,
processData: false,
async: true,
xhr: function (data) {
var xhr = new window.XMLHttpRequest(data);
xhr.upload.addEventListener("progress", function (event) {
if (event.lengthComputable) {
var percentComplete = event.loaded / event.total;
percentComplete = parseInt(percentComplete * 100);
$('#progressBardiv').text(percentComplete + '%');
$('#progressBardiv').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
beforeSend: function () {
uploadedfiles = [];
$('#editfileupload').val();
$.ajax({
type: "POST",
url: cloudServerUrl + "/api/dockstation/updatefiledisplaytimer",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
SerialNumber: $('#ddlEditDockingStationSerialNumber').val(),
FileSpinTimer: $('#txtEditTimer').val(),
IsHDMIUpdate: isHDMIUpdate
}),
complete: function () {
$('#loading-popup').hide();
$('#divEditDockingStationImages').dialog("close");
$.popup('<pre>Message</pre>', "Image Configuration Updated Successfully.", 'OK');
return false;
}
});
}
});
}
}
});
}

Ajax method working twice in a button click

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

Ajax success function not waiting on internal script to complete before leaving scope

I have this chunk of code:
$.ajax({
type: "POST",
async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {
}
}]
});
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {}
}]
});
}
});
When the ajax return success it displays the dialog box for a whole 2 seconds or so (not long enough for a user to read the message that it contains) then closes it. Using chrome's debugger, I've determined that it runs out of scope without waiting for a confirmation on the dialog box inside the success function. Does anyone know how I would go about halting the code until the user clicks ok?
Here is the full chunk of code for that ajax call..
var leZDB = null;
function zipSelectedAttachments() {
var ids = getSelectedTaskIDs();
if (ids.length > 0) {
leZDB = $.Zebra_Dialog('Do you want to zip the attachment(s)?', {
'type': 'question',
'title': 'Confirmation',
'buttons': ['Yes', 'No'],
'onClose':function (caption) {
if(caption = 'Yes') {
LinkAndPass(ids);
}
}
});
} else {
$.Zebra_Dialog('No attachments are selected.', {
'type': 'error',
'title': 'Error',
'buttons': [
{ caption: 'Ok', callback: function () { } }
]
});
}
}
function LinkAndPass(ids) {
leZDB.close();
if (true)
{
SendIDSForZipping(ids);
}
}
function SendIDSForZipping(ids) {
var csList = '';
var userID = $('#hiduserID').val();
for (var i = 0; i < ids.length; ++i) {
csList += ids[i] + ',';
}
var $this = $(this);
$this.die('click');
$.ajax({
type: "POST",
//async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID+ "'}",
contentType: "application/json; charset=utf-8",
context:this,
dataType: "json",
success: function (data) {
var hasClickedOK = false;
var hasDisplayed = false;
if (!hasDisplayed) {
hasDisplayed = true;
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
hasClickedOK = true;
}
}
]
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
}
}
]
});
}
});
}
The getSelectedIDs() returns an array of numbers.
The Code behind returns a string.
try asyn:false in $.ajax({
type: "POST",
async: true
});
The problem consisted of the web method being called from the code behind. A faulty piece of logic caused it to refresh the page, instantly closing the box.

Categories