I'm using Ajax to send form data to the server, but I'm encountering an issue where I'm getting undefined values when I try to access req.body.name on the server side. However, the file upload part is working correctly, and the files are being stored on the server. It's just the string data, such as 'name' and 'price,' that is not being received correctly.
Client-Side Code (JavaScript):
document.getElementById("submit").addEventListener("click", () => {
const data = new FormData();
for (let i = 0; i < selectedImages.length; i++) {
data.append('uploadedImages', selectedImages[i]);
}
data.append('discription', document.getElementById("discription").value);
data.append('pric', document.getElementById("pric").value);
data.append('currencyButtonTxt', document.getElementById("currencyButtonTxt").value);
console.log(data.get('pric'));
const xhr = new XMLHttpRequest();
xhr.open("POST", "/newitem", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else:
console.error("Error:", xhr.statusText);
}
};
xhr.send(data);
});
Server-Side Code (Node.js with Express):
app.post("/newitem", function (request, response) {
const name = request.body.name; // Assuming the name is in the request body
const description = request.body.discription;
const price = request.body.pric;
const currency = request.body.currencyButtonTxt;
const file = request.body.uploadedImages;
console.log("new item page all data name " + name + " description " + description + " price " + price + " currency " + currency + " the file " + file);
// Additional server-side code...
});