fraud-detection-url / static /js /url-form-handler.js
kh03's picture
Upload 7 files
0a08a10 verified
/**
* URL Form Handler
* Handles the submission of the URL form using AJAX to prevent page refreshes
*/
document.addEventListener('DOMContentLoaded', function() {
// Get form elements
const urlForm = document.getElementById('urlForm');
const urlInput = document.getElementById('urlInput');
const loadingIndicator = document.getElementById('loading');
const resultsSection = document.getElementById('results-section');
const errorContainer = document.getElementById('errorContainer');
const errorMessage = document.getElementById('errorMessage');
const errorDetails = document.getElementById('errorDetails');
const dismissErrorBtn = document.getElementById('dismissError');
console.log('URL Form Handler initialized');
// Add event listener to the form
if (urlForm) {
console.log('URL form found, adding submit handler');
urlForm.addEventListener('submit', function(e) {
e.preventDefault();
console.log('Form submission intercepted');
const url = urlInput.value.trim();
if (!url) {
console.log('Empty URL, aborting');
return;
}
// Clear any previous errors
hideError();
// Show loading indicator
if (loadingIndicator) {
loadingIndicator.style.display = 'block';
}
// Hide results section if visible
if (resultsSection) {
resultsSection.style.display = 'none';
}
console.log('Analyzing URL:', url);
// Prepare the request data
const requestData = {
url: url
};
// Make AJAX request
fetch('/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
console.log('Response received:', response.status);
return response.json().catch(error => {
console.error('Error parsing JSON response:', error);
throw new Error('Invalid JSON response from server');
});
})
.then(data => {
console.log('Analysis result:', data);
// Hide loading indicator
if (loadingIndicator) {
loadingIndicator.style.display = 'none';
}
// Enhanced error detection: Check for error status or missing required fields
if (data.status === "error" || (!data.score && !data.fraud_score)) {
console.error('Server error or incomplete data:', data);
let errorMsg = data.message || 'Incomplete data received from server';
let detailMsg = data.traceback || 'The response is missing required fields';
if (data.error) {
errorMsg = data.error;
}
showError(errorMsg, detailMsg);
return;
}
// Make sure we have the minimum data needed to display results
try {
// Display results using the displayResults function
if (window.displayResults && typeof window.displayResults.displayAllResults === 'function') {
window.displayResults.displayAllResults(data);
// Show the results section
if (resultsSection) {
resultsSection.style.display = 'block';
resultsSection.scrollIntoView({ behavior: 'smooth' });
}
} else {
console.error('displayResults function not available');
// Update analyzed URL in the results
const analyzedUrlElement = document.getElementById('analyzed-url');
if (analyzedUrlElement) {
analyzedUrlElement.textContent = url;
}
// If displayResults is not available, show the results section at minimum
if (resultsSection) {
resultsSection.style.display = 'block';
resultsSection.scrollIntoView({ behavior: 'smooth' });
}
}
} catch (displayError) {
console.error('Error displaying results:', displayError);
showError('Error displaying results', 'An error occurred while rendering the analysis results. Please try again.');
}
})
.catch(error => {
console.error('Error analyzing URL:', error);
// Hide loading indicator
if (loadingIndicator) {
loadingIndicator.style.display = 'none';
}
// More detailed error message
let errorDetails = 'Please check your connection and try again';
if (error.message) {
errorDetails = `Error details: ${error.message}`;
}
// Show error message
showError('An error occurred while analyzing the URL', errorDetails);
});
});
} else {
console.warn('URL form not found in the document');
}
// Error handling functions
function showError(message, details = '') {
if (errorContainer && errorMessage && errorDetails) {
errorMessage.textContent = message || 'An error occurred';
errorDetails.textContent = details || 'Please try again or check your connection';
errorContainer.style.display = 'block';
// Auto-scroll to error message
errorContainer.scrollIntoView({ behavior: 'smooth' });
} else {
console.error('Error message elements not found');
alert(message || 'An error occurred');
}
}
function hideError() {
if (errorContainer) {
errorContainer.style.display = 'none';
}
}
// Add event listener to dismiss error button
if (dismissErrorBtn) {
dismissErrorBtn.addEventListener('click', hideError);
}
// Add connection test functionality
// Check for test button in error message
const testConnectionBtn = document.createElement('button');
testConnectionBtn.id = 'testConnectionBtn';
testConnectionBtn.className = 'btn btn-outline-primary btn-sm ms-2';
testConnectionBtn.textContent = 'Test Connection';
testConnectionBtn.style.marginLeft = '8px';
// Add it to the error container if it exists
if (errorContainer && !document.getElementById('testConnectionBtn')) {
const errorActions = document.createElement('div');
errorActions.className = 'error-actions';
errorActions.style.marginTop = '15px';
errorActions.style.display = 'flex';
errorActions.style.justifyContent = 'flex-end';
errorActions.appendChild(testConnectionBtn);
if (dismissErrorBtn) {
dismissErrorBtn.style.marginLeft = '8px';
errorActions.appendChild(dismissErrorBtn);
}
errorContainer.appendChild(errorActions);
}
// Add event listener for connection test
testConnectionBtn.addEventListener('click', function() {
console.log('Testing connection to backend...');
// Show a small loading indicator in the button
testConnectionBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Testing...';
testConnectionBtn.disabled = true;
// Test basic connection with simple GET request
fetch('/debug-connection')
.then(response => response.json())
.then(data => {
console.log('Connection test GET result:', data);
// Now try a POST request with actual payload
return fetch('/debug-connection', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({test: true, timestamp: new Date().toISOString()})
});
})
.then(response => response.json())
.then(data => {
console.log('Connection test POST result:', data);
// Show success message
testConnectionBtn.innerHTML = '<i class="fas fa-check"></i> Connection OK';
testConnectionBtn.className = 'btn btn-success btn-sm ms-2';
// Reset after a delay
setTimeout(() => {
testConnectionBtn.textContent = 'Test Connection';
testConnectionBtn.className = 'btn btn-outline-primary btn-sm ms-2';
testConnectionBtn.disabled = false;
// Update error message
errorMessage.textContent = 'Connection to server is working';
errorDetails.textContent = 'Try submitting your URL again. If the error persists, the issue may be with processing your specific URL.';
}, 2000);
})
.catch(error => {
console.error('Connection test failed:', error);
// Show error
testConnectionBtn.innerHTML = '<i class="fas fa-times"></i> Failed';
testConnectionBtn.className = 'btn btn-danger btn-sm ms-2';
// Reset after a delay
setTimeout(() => {
testConnectionBtn.textContent = 'Test Connection';
testConnectionBtn.className = 'btn btn-outline-primary btn-sm ms-2';
testConnectionBtn.disabled = false;
// Update error message with more details
errorMessage.textContent = 'Connection to server failed';
errorDetails.textContent = `Error details: ${error.message}. Please check your network connection or server status.`;
}, 2000);
});
});
});