$(document).ready(function () {
loadList();
// Event delegation for delete buttons
$('#DT_load').on('click', '.delete-button', function () {
const rowIndex = dataTable.row($(this).closest('tr')).index();
const id = $(this).data('id');
DeleteRow(rowIndex, id);
});
});
function loadList() {
var url = new URL(window.location.href);
var SampleAnalyzeId = url.searchParams.get("id");
dataTable = $('#DT_load').DataTable({
"ajax": {
"url": "/api/SampleAnalyzeFile/" + SampleAnalyzeId,
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "File", "width": "25%" },
{ "data": "FileName", "width": "10%" },
{ "data": "FileExtention", "width": "10%" },
{
"data": "Id",
"render": function (data, type, row, meta) {
return `<div class="text-center">
<button class="btn btn-danger text-white delete-button" data-id="${data}" style="cursor:pointer;" type="button">
حذف <i class="glyphicon glyphicon-trash"></i>
</button>
</div>`;
},
"width": "15%"
}
],
bLengthChange: false,
paging: true,
searching: false,
ordering: true,
"language": {
"url": "/js/PersianDataTable.json"
},
"width": "100%"
});
}
function DeleteRow(rowIndex, id) {
swal({
title: "از حذف مطمئن هستید؟",
icon: "warning",
buttons: true,
dangerMode: true
}).then((willDelete) => {
if (willDelete) {
// Remove row from DataTable and redraw
dataTable.row(rowIndex).remove().draw();
// Collect remaining rows into dataList
dataList = [];
dataTable.rows().every(function () {
const rowData = this.data();
dataList.push({
"Id": rowData['Id'],
"File": rowData['File'],
"FileName": rowData['FileName'],
"FileExtention": rowData['FileExtention'],
});
});
// Prepare FormData with id and dataList
const formData = new FormData();
formData.append("Id", id);
formData.append("DataList", JSON.stringify(({ list: dataList })));
// Send data to the server
const csrfToken = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
type: "POST",
url: "?handler=Delete",
data: formData,
contentType: false,
processData: false,
headers: {
"RequestVerificationToken": csrfToken
},
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", csrfToken);
},
success: function (response) {
if (response.success) {
swal("با موفقیت حذف شد!", { icon: "success" });
} else {
swal("خطا در حذف رکورد: " + response.message, { icon: "error" });
}
},
error: function (error) {
console.error("Error in AJAX request:", error);
swal("خطا در ارتباط با سرور!", { icon: "error" });
}
});
}
});
}
const data = {}
function generateGUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// Function to generate a simple hash
function generateHash(input) {
let hash = 0;
for (let i = 0; i < input.length; i++) {
let char = input.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash |= 0; // Convert to 32-bit integer
}
return hash.toString(16);
}
function AddSampleAnalyzeFile(prevData) {
// Step 1: Validate input fields
if (!validateInput()) {
return false;
}
// Step 2: Get the file input element and the selected file
const fileInput = document.getElementById('HasFile');
if (!fileInput || fileInput.files.length === 0) {
alert("Please select a file to upload.");
return false;
}
const file = fileInput.files[0];
const fullFileName = file.name;
const fileName = fullFileName.substring(0, fullFileName.lastIndexOf('.'));
const fileExtension = fullFileName.split('.').pop();
// Step 3: Generate GUID and hash for the file (Implement these functions as needed)
const fileGUID = generateGUID();
const fileHash = generateHash(fileGUID);
const fileNameWithHash = `${fileName}(${fileHash}).${fileExtension}`;
// Step 4: Create a new File object with the hashed name
const renamedFile = new File([file], fileNameWithHash, { type: file.type });
// Step 5: Initialize or get the existing DataTable
var table = $('#DT_load').DataTable();
// Step 6: Add the renamed file info to the DataTable
table.row.add({
File: fileNameWithHash,
FileName: fileName,
FileExtention: fileExtension
}).draw();
// Step 7: Construct the data array from the DataTable rows
let data = [];
table.rows().every(function (rowIdx, tableLoop, rowLoop) {
var rowData = this.data();
data.push({
"File": rowData['File'],
"FileName": rowData['FileName'],
"FileExtention": rowData['FileExtention']
});
});
// Step 8: Prepare the FormData object
var formData = new FormData();
formData.append("UploadedFiles", renamedFile); // Append the file
// Step 9: Append the data list as a JSON string
formData.append("DataList", JSON.stringify({ list: data }));
// Step 10: Include the anti-forgery token for security
var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val();
if (antiForgeryToken) {
formData.append("__RequestVerificationToken", antiForgeryToken);
}
// Step 11: Perform the AJAX POST request
$.ajax({
type: "POST",
url: "?handler=FileSend", // Backend handler URL
data: formData,
contentType: false, // Required for FormData
processData: false, // Required for FormData
success: function (response) {
console.log("File and data uploaded successfully:", response);
alert("File and data uploaded successfully.");
// Optionally, reset the form or clear the DataTable here
},
error: function (jqXHR, textStatus, errorThrown) {
console.error("Error in uploading file and data:", textStatus, errorThrown);
alert("An error occurred while uploading the file and data. Please try again.");
}
});
return true; // Indicate that the function executed successfully
}