Register a Worker
Add Apartment
Additional Information
Name:
Aadhar Number:
Mobile Number:
Gender:
Male
Female
Services:
Maid
Nanny
Cook
Book Slots and Submit Form
const slotsContainer = document.getElementById("slots");
const tagInput = document.getElementById("tag-input");
const addTagButton = document.getElementById("add-tag");
const submitButton = document.getElementById("submit-button");
const startTime = 6; // Start time (6:00 AM)
const endTime = 30; // End time (6:00 AM of the next day)
const timeSlots = [];
const selectedTimeSlots = [];
const selectedTags = [];
// Generate time slots with 1-hour intervals
for (let i = startTime; i < endTime; i++) {
const slotStartTime = i % 24;
const slotEndTime = (i + 1) % 24;
const slotLabel = `${slotStartTime.toString().padStart(2, '0')}:00 - ${slotEndTime.toString().padStart(2, '0')}:00`;
timeSlots.push(slotLabel);
}
timeSlots.forEach((slot) => {
const slotElement = document.createElement("div");
slotElement.classList.add("slot");
slotElement.textContent = slot;
slotElement.addEventListener("click", () => {
slotElement.classList.toggle("selected");
if (slotElement.classList.contains("selected")) {
selectedTimeSlots.push(slot);
} else {
selectedTimeSlots = selectedTimeSlots.filter((time) => time !== slot);
}
});
slotsContainer.appendChild(slotElement);
});
// Predefined tags
const predefinedTags = ["RPH", "SOMU SONNET", "PFR", "AS"];
function displayTags() {
const searchTagsContainer = document.querySelector(".search-tags");
searchTagsContainer.innerHTML = "";
selectedTags.forEach((tag) => {
const tagSpan = document.createElement("span");
tagSpan.textContent = tag;
tagSpan.addEventListener("click", () => {
// Remove the tag when clicked
selectedTags.splice(selectedTags.indexOf(tag), 1);
displayTags();
});
searchTagsContainer.appendChild(tagSpan);
});
}
// Function to populate the datalist with predefined tags
function populateDatalist() {
const datalist = document.getElementById("tags-list");
datalist.innerHTML = "";
predefinedTags.forEach((tag) => {
const option = document.createElement("option");
option.value = tag;
datalist.appendChild(option);
});
}
// Display predefined tags in the datalist
populateDatalist();
addTagButton.addEventListener("click", () => {
const tag = tagInput.value.trim();
if (tag !== "" && !selectedTags.includes(tag)) {
selectedTags.push(tag);
tagInput.value = "";
displayTags();
}
});
submitButton.addEventListener("click", () => {
// Prepare the data to send
const name = document.getElementById("name").value;
const aadhar = document.getElementById("aadhar").value;
const mobile = document.getElementById("mobile").value;
const gender = document.querySelector('input[name="gender"]:checked').value;
const services = [...document.querySelectorAll('input[name="services"]:checked')].map((checkbox) => checkbox.value);
const data = {
aadhar_number: aadhar,
name: name,
phone_number: mobile,
gender: gender,
services: services.join(', '),
locations: selectedTags.join(', '),
timings: selectedTimeSlots.join(', '),
};
// Send the data to the specified form URL
sendDataToFormester(data);
});
function sendDataToFormester(data) {
const formesterFormUrl = 'https://yellowsensebackendapi.azurewebsites.net/insert_maid';
fetch(formesterFormUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Set the content type to JSON
},
body: JSON.stringify(data), // Convert data to a JSON string
})
.then(() => {
alert('Data submitted successfully to YellowSense.');
})
.catch((error) => {
console.error('Error:', error);
alert('An error occurred while submitting data.');
});
}
пожалуйста, сообщите мне, в чем здесь ошибка и как ее устранить. В коде нет проблем с CORS, поскольку он возвращает следующий успешный результат:
[img]https://i.stack.imgur. com/8dsLh.png[/img]
Я постоянно получаю эту ошибку при отправке запроса POST к API Flask: [code]{ "error": "415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not 'application/json'." } [/code] Это мой код Python API Flask, который я хочу вызвать, чтобы внести данные в базу данных SQL Azure: [code]from flask import Flask, request, jsonify from flask_cors import CORS, cross_origin import pyodbc
try: conn = pyodbc.connect(connectionString) cursor = conn.cursor() except pyodbc.Error as e: print("Error connecting to the database:", e)
# Function to add custom headers to every response @app.after_request def add_headers(response): response.headers['Access-Control-Allow-Origin'] = 'https://yellowsense.in' # Replace with your frontend domain response.headers['Access-Control-Allow-Methods'] = 'GET, POST' # You can specify the allowed methods response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization' # You can specify the allowed headers return response
@app.route('/society_names', methods=['GET']) @cross_origin() def get_society_names(): try: # Execute a SQL query to retrieve society names and IDs cursor.execute("SELECT society_id, society_name FROM Society") rows = cursor.fetchall()
# Convert the result into an array of dictionaries with id and name society_data = [{"id": row.society_id, "name": row.society_name} for row in rows]
return jsonify(society_data) # Return JSON with id and name except pyodbc.Error as e: return jsonify({"error": str(e)})
const startTime = 6; // Start time (6:00 AM) const endTime = 30; // End time (6:00 AM of the next day) const timeSlots = []; const selectedTimeSlots = []; const selectedTags = [];
// Generate time slots with 1-hour intervals for (let i = startTime; i < endTime; i++) { const slotStartTime = i % 24; const slotEndTime = (i + 1) % 24; const slotLabel = `${slotStartTime.toString().padStart(2, '0')}:00 - ${slotEndTime.toString().padStart(2, '0')}:00`; timeSlots.push(slotLabel); }
// Send the data to the specified form URL sendDataToFormester(data); });
function sendDataToFormester(data) { const formesterFormUrl = 'https://yellowsensebackendapi.azurewebsites.net/insert_maid';
fetch(formesterFormUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', // Set the content type to JSON }, body: JSON.stringify(data), // Convert data to a JSON string }) .then(() => { alert('Data submitted successfully to YellowSense.'); }) .catch((error) => { console.error('Error:', error); alert('An error occurred while submitting data.'); }); } [/code] пожалуйста, сообщите мне, в чем здесь ошибка и как ее устранить. В коде нет проблем с CORS, поскольку он возвращает следующий успешный результат: [img]https://i.stack.imgur. com/8dsLh.png[/img]
Я работаю над проектом React-Python(Flask). Я продолжаю получать сообщение об ошибке «415 Неподдерживаемый тип носителя: не пытался загрузить данные JSON, поскольку тип контента запроса не был «application/json». Я не знаю, связана ли проблема с...
Итак, я работаю над проектом со своим другом, и мы столкнулись с проблемой. У меня есть переменная в JavaScript, и она мне нужна в Python, поэтому я создал колбу и запрос на публикацию, но при ее запуске у меня возникает ошибка. Я пробовал искать...
Итак, я работаю над проектом со своим другом, и мы столкнулись с проблемой. У меня есть переменная в JavaScript, и она мне нужна в Python, поэтому я создал колбу и запрос на публикацию, но при ее запуске у меня возникает ошибка. Я пробовал искать...