I have been working for this project over a month, and now I can’t fix the issue where it is not possible to correctly retrieve or send the variable ‘barber_id’ to Flask app. Overall, the JS code was generated by ChatGPT(because I’m new to JS). My main purpose is to get suggestions for barbershop name, barber name, haircut name(which each barber can perform differently) from Postgresql database WHILE I am typing in input fields dynamically. First of all, I have great struggles with sending a ‘barbershop_id’ to Flask app, but then I **fixed **it by choosing a barbershop-name from suggestions and retrieve its corresponding values from database. But now it is absolutely not possible to handle the ‘barber_id’ correctly, I have used almost all types of AI to help, but they didn’t useful at all.
Here is part of code which is problematic:
HTML code (partly):
<!-- Add Appointment Section -->
<div class="card mb-3">
<div class="card-header d-flex justify-content-between align-items-center">
Add Appointment
<button class="btn btn-link p-0" id="toggle-add-appointment-btn">
<i class="fas fa-plus"></i>
</button>
</div>
<div class="card-body" id="add-appointment-content" style="display: none;">
<form id="add-appointment-form" method="POST" action="{{ url_for('permissions.add_appointment') }}">
<div class="form-group">
<label for="add-appointment-barbershop-name">Barbershop name</label>
<input type="text" class="form-control" id="add-appointment-barbershop-name" name="add-appointment-barbershop-name" required>
<div id="barbershop-suggestions" class="suggestions"></div>
</div>
<div class="form-group">
<label for="barber-name">Barber Name</label>
<input type="text" class="form-control" id="barber-name" name="barber-name" required><!-- THE ISSUE IS HERE -->
<div id="barber-suggestions" class="suggestions"></div>
</div>
<div class="form-group">
<label for="customer-first-name">Customer First Name</label>
<input type="text" class="form-control" id="customer-first-name" name="customer-first-name" required>
</div>
<div class="form-group">
<label for="customer-last-name">Customer Last Name</label>
<input type="text" class="form-control" id="customer-last-name" name="customer-last-name">
</div>
<div class="form-group">
<label for="customer-phone-number">Customer Phone Number</label>
<input type="tel" class="form-control" id="customer-phone-number" name="customer-phone-number">
</div>
<div class="form-group">
<label for="add-appointment-haircut-name">Haircut Name</label>
<input type="text" class="form-control" id="add-appointment-haircut-name" name="add-appointment-haircut-name" required>
<div id="haircut-suggestions" class="suggestions"></div>
</div>
<div class="form-group">
<label for="appointment-day">Appointment Date</label>
<input type="date" id="appointment-day" name="appointment-day">
</div>
<div class="form-group">
<label for="appointment-time">Appointment Time</label>
<select id="appointment-time" name="appointment_time" required>
<option value="">Select a time</option>
<!-- Available times will be populated here -->
</select>
</div>
<div class="form-group">
<label for="duration-minutes">Duration (Minutes)</label>
<input type="number" class="form-control" id="duration-minutes" name="duration_minutes"
value="45" required>
</div>
<!-- Hidden fields for storing IDs and names -->
<input type="hidden" id="barbershop-id-hidden" name="barbershop_id">
<input type="hidden" id="barber-id-hidden" name="barber_id"><!-- THE ISSUE IS HERE -->
<button type="submit" class="btn btn-primary">Add Appointment</button>
</form>
</div>
</div>
My JavaScript code(partly):
document.getElementById('add-appointment-barbershop-name').addEventListener('input', function() {
fetchSuggestions('barbershop', this.value, 'add-appointment-barbershop-name', 'barbershop-suggestions');
});
document.getElementById('barber-name').addEventListener('input', function() {
// Retrieve the barbershop and barber IDs from the hidden input fields
let barbershopId = document.getElementById('barbershop-id-hidden').value;
let barberId = document.getElementById('barber-id-hidden').value;
// Capture the value of the input field
let queryValue = this.value;
// Debugging: Check the values before proceeding
console.log("Barbershop ID:", barbershopId);
console.log("Barber ID:", barberId);
console.log("Query Value:", queryValue);
// Proceed with the fetch if queryValue is defined
if (queryValue) {
fetchSuggestions('barber', `${queryValue}&barbershop_id=${barbershopId}&barber_id_hidden=${barberId}`, 'barber-name', 'barber-suggestions');
} else {
console.error('Query value is undefined');
}
});
document.getElementById('add-appointment-haircut-name').addEventListener('input', function() {
fetchSuggestions('haircut', this.value, 'add-appointment-haircut-name', 'haircut-suggestions');
});
function fetchSuggestions(type, query, inputFieldId, suggestionDivId) { // HERE IS THE MAIN //PROBLEMATIC FUNCTION!!!
let suggestionDiv = document.getElementById(suggestionDivId);
if (query.trim() === '') {
suggestionDiv.innerHTML = '';
return;
}
fetch(`/get-suggestions/${type}?q=` + query)
.then(response => response.json())
.then(data => {
suggestionDiv.innerHTML = ''; // Clear previous suggestions
data.forEach((item, index) => {
let div = document.createElement('div');
if (type === 'barbershop') {
div.textContent = item.barbershop_name;
} else if (type === 'barber') {
div.textContent = item.barber_name;
} else {
div.textContent = item; // For other types like haircut, where the data is just a string
}
div.classList.add('suggestion-item');
div.addEventListener('click', function() {
document.getElementById(inputFieldId).value = this.textContent;
// Correctly set barbershop ID if selecting a barbershop
if (type === 'barbershop') {
document.getElementById('barbershop-id-hidden').value = data[index].barbershop_id;
console.log("Assigned barbershop_id:", item.barbershop_id); // Debugging output
}
// For barbers, you can store barber_id if needed
if (type === 'barber') {
form.addEventListener('submit', function (event) {
console.log("Submitting form with barber_id:", document.getElementById('barber-id-hidden').value);
// proceed with form submission
});
let barberIdInput = document.getElementById('barber-id-hidden');
if (barberIdInput) {
barberIdInput.value = item.barber_id;
document.getElementById('barber-id-hidden').value = data[index].barber_id;
let barbershopId = document.getElementById('barbershop-id-hidden').value;
let barberId = document.getElementById('barber-id-hidden').value;
// Debugging: Check the values before proceeding
console.log("Barbershop ID:", barbershopId);
console.log("Barber ID:", barberId);
console.log("Constructed URL:", `/get-suggestions/barber?q=${item.barber_name}&barbershop_id=${barbershopId}&barber_id_hidden=${barberId}`);
} else {
console.error('Hidden input for barber_id not found.');
}
}
suggestionDiv.innerHTML = ''; // Clear suggestions after selection
});
suggestionDiv.appendChild(div);
});
})
.catch(error => console.error('Error loading suggestions:', error));
}
and finally, my Flask app code(partly):
@permissions.route('/get-suggestions/<type>', methods=['GET'])
def get_suggestions(type):
query = request.args.get('q', '')
if type == 'barbershop':
cur.execute("SELECT barbershop_name, barbershop_id FROM barbershops WHERE barbershop_name ILIKE %s",
(f'%{query}%',))
results = cur.fetchall()
print(f"results: {results}")
return flask_jsonify([{"barbershop_name": result[0], "barbershop_id": result[1]} for result in results])
elif type == 'barber':
barbershop_id = request.args.get('barbershop_id')
**barber_id = request.args.get('barber_id') NOT WORKED
# barber_id = request.args.get('barber_id-hidden') NOT WORKED
# barber_id = request.form.get('barber-id') NOT WORKED
# barber_id = request.form.get('barber-id-hidden') NOT WORKED
# barber_id = request.form.get('barber_id') NOT WORKED
# barber_id = request.args.get('barber_id') NOT WORKED**
print("Received barber_id:", barber_id) # Debugging output RESULTS IS: None **(IT SHOULD BE INTEGER TYPE)**
print(f"Request args: {request.args}") # Print all query parameters
print(f"type barber: barbershop_id: {barbershop_id}, barber_id: {barber_id}")
if barbershop_id:
cur.execute(
"SELECT barber_first_name, barber_id FROM barbers WHERE barber_first_name ILIKE %s AND barbershop_id = %s",
(f'%{query}%', barbershop_id))
results = cur.fetchall()
print(f"results barber: {results}")
return flask_jsonify([{"barber_name": result[0], "barber_id": result[1]} for result in results])
else:
return flask_jsonify([]) # No barbershop ID provided
elif type == 'haircut':
cur.execute("SELECT haircut_name FROM haircuts WHERE haircut_name ILIKE %s LIMIT 10", (f'%{query}%',)) #** I NEED A BARBER_ID TO CORRECTLY GET A HAIRCUT NAME FROM DATABASE WHICH EACH BARBER CAN PERFORM**
return flask_jsonify([result[0] for result in cur.fetchall()])
I have tried almost every AI(mostly ChatGPT), but they didn’t help me. I am expecting that I’ll receive a ‘barber_id’ as a integer(just like a barbershop_id). If you need a full code, just tell and I’ll send.