عملت هذه الخطوات
هذا الكود للبايثون:
@app.route('/save_data', methods=['POST'])
def save_data():
try:
data = request.get_json()
product_name = data['productName']
ingredient = data['ingredient']
date_value = data['date']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO products (ProductName, ExpiryDate, Ingredient) VALUES (%s, %s, %s)", (product_name, ingredient, date_value))
mysql.connection.commit()
cur.close()
return jsonify({"message": "Data saved successfully"}), 200
except Exception as e:
print("Exception:", e)
return jsonify({"error": str(e)}), 500
وهذا الكود للجافاسكربت:
async function confirmSave() {
if (confirm("Are you sure you want to save the data?")) {
const productName = prompt("Please enter the name of the product:");
if (productName !== null && productName.trim() !== "") {
await saveData(productName);
} else {
alert("Product name cannot be empty.");
}
}
}
async function saveData(productName) {
const containers = document.querySelectorAll('.container');
let ingredient = '';
let date = '';
let algrency = '';
containers.forEach((container, index) => {
const textBox = container.querySelector('.text-box');
const value = textBox.value.trim();
switch(index) {
case 0:
ingredient = value;
break;
case 1:
date = value;
break;
case 2:
algrency = value;
break;
}
});
// Prepare data to send
const postData = {
productName: productName,
ingredient: ingredient,
date: date,
};
try {
const response = await fetch('/save_data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const responseData = await response.json();
console.log(responseData.message); // Log the response message
} catch (error) {
console.error('Error:', error);
}
console.log("Product Name:", productName);
console.log("Ingredient:", ingredient);
console.log("date:", date);
console.log("Algrency:", algrency);
}
ما هي المشكلة؟