let socket_id = "{{md5(Str::random(40))}}";
let node_url = "http://41.33.3.35:4433";
let engines = ['Google','Bing','Duck'];
let social = ['Telegram','Twitter','Instagram'];
let socialId = [1,6];
let enginesId = [3,4,5];
let viewbtn = document.getElementById('viewbtn')
let table =document.getElementById('latestSearches');
});
})}) make the fetch request only can be executed just once of viewpage and send full code
To ensure that the fetch request associated with each .viewbtn is executed only once, you can modify the click event handler to disable the button after it's clicked. This prevents multiple fetch requests from being sent if the user clicks the button multiple times.
Below is the full modified code with the necessary changes applied. I've added comments to highlight the key modifications:
javascript
let socket_id = "{{md5(Str::random(40))}}";
let node_url = "http://41.33.3.35:4433";
let engines = ['Google','Bing','Duck'];
let social = ['Telegram','Twitter','Instagram'];
let socialId = [1,6];
let enginesId = [3,4,5];
let viewbtn = document.getElementById('viewbtn');
let table = document.getElementById('latestSearches');
$(document).ready(function () {
// Corrected the selector to target elements with the 'viewbtn' class
viewbtns = document.querySelectorAll('.viewbtn'); // Added '.' before 'viewbtn'
// Event delegation for dynamically added '.viewbtn' elements
$(document).on('click', '.viewbtn', function() {
let $btn = $(this);
// Check if the button has already been clicked
if ($btn.data('clicked')) {
return; // If already clicked, do nothing
}
// Mark the button as clicked
$btn.data('clicked', true);
// Optionally disable the button to prevent further clicks
$btn.prop('disabled', true);
$btn.text('Processing...'); // Optional: Change button text for feedback
let $row = $btn.closest('tr');
let cellValue = $row.find('td').eq(3).text().trim();
console.log(cellValue);
fetch('/view-page', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify({ "createdat": cellValue })
})
.then(response => response.json()) // Assuming the server returns JSON
.then(data => {
// Handle the response data if needed
console.log('Fetch successful:', data);
setTimeout(() => {
window.location.href = 'box-viewer';
}, 2000);
})
.catch(error => {
console.error('Error during fetch:', error);
// Optionally re-enable the button if there was an error
$btn.prop('disabled', false);
$btn.text('View'); // Reset button text
$btn.data('clicked', false);
});
});
$('.searchBtn').on('click', function () {
$(document).ready(function () {
$('.searchBtn').on('click', function () {
var brandID = $(this).val();
let searchBtnDiv = $(this).closest('.searchBtnDiv');
let loadingBtnDiv = $(this).parent().siblings('.loadingBtnDiv');
let form = $(this).closest('.searchForm');
formattedDateTime = "";
function getFormattedCurrentDateTime() {
const now = new Date();
now.setHours(now.getHours() + 7);
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
formattedDateTime = `${year}_${month}_${day}_${hours}_${minutes}_${seconds}`;
return formattedDateTime;
}
console.log(getFormattedCurrentDateTime());
if (document.querySelector("#socialForm.active")) {
if (document.querySelector("#socialForm select[name=type]").value === "facebook") {
let keywords = document.querySelector("#socialForm input[name=keyword]").value.split(',');
keywords = keywords.map(function(keyword) {
return keyword.trim();
});
searchBtnDiv.addClass('d-none');
loadingBtnDiv.removeClass('d-none');
let totalKeywords = keywords.length;
let processedKeywords = 0;
keywords.forEach(function(keyword) {
let keywordSocketId = socket_id + '_' + keyword.replace(/\s+/g, '_');
let setInter = setInterval(() => {
$.ajax({
url: "{{route('facebookExist', '')}}/" + keywordSocketId,
type: "POST",
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({
_token: "{{csrf_token()}}",
socket_id: keywordSocketId,
keyword: keyword,
sort: document.querySelector("#socialForm select[name=facebook_sort]").value,
searchLimit: document.querySelector("#socialForm select[name=results]").value
}),
success: function(data2, status) {
console.log("Checking status for keyword: " + keyword);
if (data2.status) {
data = data2.data;
console.log(data);
clearInterval(setInter);
$.ajax({
type: 'post',
url: "{{route('searchFacebook')}}",
data: {
_token: "{{csrf_token()}}",
data
},
success: function (response) {
console.log(response);
$('#latestSearches').removeClass('d-none');
$.each(response, function (index, dataItem) {
$('#latestSearches > tbody').prepend('<tr> <td><i class="'+dataItem.type_icon+'"></i></td> <td>'+dataItem.type_name+'</td> <td>'+dataItem.keyword+'</td> <td>'+formattedDateTime+'</td> <td>'+dataItem.results+' <a class="downloadBtn" href="'+dataItem.file+'"><i class="ms-2 fas fa-download"></i></a></td></tr>');
});
processTableData();
processedKeywords++;
if (processedKeywords === totalKeywords) {
searchBtnDiv.removeClass('d-none');
loadingBtnDiv.addClass('d-none');
}
},
error: function(e) {
console.log(e);
processedKeywords++;
if (processedKeywords === totalKeywords) {
searchBtnDiv.removeClass('d-none');
loadingBtnDiv.addClass('d-none');
}
}
});
}
},
error: function(e) {
console.log(e);
}
});
}, 2000);
$.ajax({
url: "{{route('facebookApi')}}",
type: "POST",
data: {
_token: "{{csrf_token()}}",
socket_id: keywordSocketId,
keyword: keyword,
sort: document.querySelector("#socialForm select[name=facebook_sort]").value,
searchLimit: document.querySelector("#socialForm select[name=results]").value
},
success: function(data, status) {
console.log("Started search for keyword: " + keyword);
}
});
});
}
} else if (document.querySelector("#trendsForm.active")) {
searchBtnDiv.addClass('d-none');
loadingBtnDiv.removeClass('d-none');
let keywords = document.querySelector("#trendsForm input[name=keyword]").value.split(',');
keywords = keywords.map(function(keyword) {
return keyword.trim();
});
let totalKeywords = keywords.length;
let processedKeywords = 0;
keywords.forEach(function(keyword) {
let fd = new FormData();
fd.append('socket_id', socket_id);
fd.append('keyword', keyword);
$.ajax({
url: "{{route('trendsApi')}}",
type: "POST",
headers: {
'Content-Type': 'application/json',
},
data: JSON.stringify({
_token: "{{csrf_token()}}",
socket_id: socket_id,
keyword: keyword
}),
contentType: false,
processData: false,
success: function(data, status) {
console.log(data);
document.querySelector("#trendsSearch input[name=json]").value = JSON.stringify(data.data);
document.querySelector("#trendsSearch").submit();
processedKeywords++;
if (processedKeywords === totalKeywords) {
searchBtnDiv.removeClass('d-none');
loadingBtnDiv.addClass('d-none');
}
},
error: function(e) {
console.log(e);
processedKeywords++;
if (processedKeywords === totalKeywords) {
searchBtnDiv.removeClass('d-none');
loadingBtnDiv.addClass('d-none');
}
}
});
});
} else {
let keywords = form.find('input[name="keyword"]').val().split(',');
keywords = keywords.map(function(keyword) {
return keyword.trim();
});
let totalKeywords = keywords.length;
let processedKeywords = 0;
keywords.forEach(function(keyword) {
let formData = form.serializeArray();
formData = formData.filter(function(item) {
return item.name !== 'keyword';
});
formData.push({ name: 'keyword', value: keyword });
$.ajax({
type: 'post',
url: form.attr('action'),
data: $.param(formData),
success: function (response) {
console.log(response);
if (response.error)
alert(response.error);
else {
getFormattedCurrentDateTime();
$('#latestSearches').removeClass('d-none');
$.each(response, function (index, dataItem) {
$('#latestSearches > tbody').prepend('<tr> <td><i class="'+dataItem.type_icon+'"></i></td> <td>'+dataItem.type_name+'</td> <td>'+dataItem.keyword+'</td> <td>'+formattedDateTime+'</td> <td>'+dataItem.results+' <a class="downloadBtn" href="'+dataItem.file+'"><i class="ms-2 fas fa-download"></i></a></td> <td><button class="viewbtn">View</button></td></tr>');
});
processTableData();
}
processedKeywords++;
if (processedKeywords === totalKeywords) {
searchBtnDiv.removeClass('d-none');
loadingBtnDiv.addClass('d-none');
}
},
beforeSend: function () {
searchBtnDiv.addClass('d-none');
loadingBtnDiv.removeClass('d-none');
},
error: function(e) {
console.log(e);
alert("Error while exporting");
processedKeywords++;
if (processedKeywords === totalKeywords) {
searchBtnDiv.removeClass('d-none');
loadingBtnDiv.addClass('d-none');
}
}
});
});
}
});
});
function processTableData() {
var $table = $('#latestSearches');
var headers = [];
$table.find('tr:first').find('th, td').each(function() {
headers.push($(this).text().trim());
});
var data = [];
$table.find('tr').each(function(index) {
if (index === 0) return;
var $row = $(this);
var $cells = $row.find('td');
var rowData = {};
$cells.each(function(cellIndex) {
var header = headers[cellIndex] || 'Column' + (cellIndex + 1);
rowData[header] = $(this).text().trim();
});
if (!$.isEmptyObject(rowData)) {
data.push(rowData);
}
});
console.log('Data to be sent:', data);
var csrfToken = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: '/history-view',
method: 'POST',
data: {
data: data,
_token: csrfToken
},
success: function(response) {
console.log('Success:', response);
},
error: function(xhr, status, error) {
console.error('Error:', xhr.responseText);
}
});
}
$('#select_search').on('change', function () {
if ($(this).val() == "top") {
$('#dateFrom').prop('disabled', false).parent().removeClass('d-none');
$('#dateTo').prop('disabled', false).parent().removeClass('d-none');
$('#profileTxt').prop('disabled', 'disabled').parent().addClass('d-none');
} else if($(this).val() == 'profile'){
$('#profileTxt').prop('disabled', false).parent().removeClass('d-none');
} else {
$('#profileTxt').prop('disabled', 'disabled').parent().addClass('d-none');
$('#dateFrom').prop('disabled', 'disabled').parent().addClass('d-none');
$('#dateTo').prop('disabled', 'disabled').parent().addClass('d-none');
}
});
$(".social_media_form select[name=type]").on('change', function() {
if($(this).val() == "facebook") {
$("#facebookSort").css('display', 'block');
$("#sort").css('display', "none");
} else {
$("#facebookSort").css('display', 'none');
$("#sort").css('display', "block");
}
});
// Trigger change event on page load to set the correct display
document.querySelector(".social_media_form select[name=type]").dispatchEvent(new Event('change'));
$(document).on('change','#platformSel',function (){
if($(this).val() === 'Google' || $(this).val() === 'Bing' || $(this).val() === 'Duck'){
$('#sortSel').prop('disabled',true);
$('#dateFrom').prop('disabled', 'disabled').parent().addClass('d-none');
$('#dateTo').prop('disabled', 'disabled').parent().addClass('d-none');
} else {
$('#sortSel').prop('disabled', false);
}
if($(this).val() !== 'twitter') {
$('#profileTxt').prop('disabled', 'disabled').parent().addClass('d-none');
}
});
$(document).on('submit','#searchForm',function(e) {
e.preventDefault();
$('#searchBtn').trigger('click');
});
$(document).on('click','.downloadBtn',function (){
$(this).parents('tr').remove();
if ($('#latestSearches > tbody tr').length == 0){
$('#latestSearches').addClass('d-none');
}
});
});
});
Key Modifications Explained:
Corrected Selector for .viewbtn:
Changed document.querySelectorAll('viewbtn') to document.querySelectorAll('.viewbtn') to properly select elements with the viewbtn class.
Preventing Multiple Fetch Requests:
Data Attribute Check: Before proceeding with the fetch, the script checks if the button has already been clicked by using a data attribute (data('clicked')). If it's already clicked, the function returns early, preventing another fetch.
Marking as Clicked: After confirming it's the first click, the button is marked as clicked by setting data('clicked', true).
Disabling the Button: The button is disabled using .prop('disabled', true) to prevent further interactions.
Feedback to User: Optionally, the button text is changed to "Processing..." to provide visual feedback that an action is in progress.
Error Handling: If the fetch fails, the button is re-enabled, and the data('clicked') attribute is reset, allowing the user to try again.
Enhanced Error Handling for Fetch:
Added a .catch block to handle any errors that occur during the fetch. This ensures that if an error occurs, the button is re-enabled, and the user can attempt the action again.
Improved Event Delegation:
Ensured that the click event for .viewbtn is delegated properly, which is especially important for dynamically added buttons.
General Code Cleanup:
Added comments for better readability.
Ensured consistent indentation and formatting for easier maintenance.
Additional Recommendations:
User Feedback:
Consider adding a spinner or some visual indicator inside the button when it's in the "Processing..." state to improve user experience.
Accessibility:
Ensure that disabling the button does not affect accessibility. For instance, screen readers should announce the button's state appropriately.
Optimizing Event Listeners:
Review the nested $(document).ready(function () { ... }); and redundant event bindings to optimize performance and prevent potential memory leaks.
Implementing these changes will ensure that each .viewbtn can only execute the fetch request once, enhancing both the performance and reliability of your application.