In my current project using Django Python/Javascript, I'm facing an issue with the PUT request. The request is successfully sent to the server by the client, but after that, the page automatically refreshes, exposing the csrf token middleware in the URL. I've tried various solutions such as implementing AJAX, using returning false, adding event.preventDefault(), passing a cookie through the fetch header, utilizing async functions, and incorporating a try and catch syntax. Despite all these efforts, I can't seem to prevent the webpage from refreshing and displaying the csrf_token appended to the URL upon submission.
If anyone has any insights or suggestions on what might be missing here, I would greatly appreciate it! Thank you!
// Define global variables for form submission
var id, upt_prodName, upt_prodPrice, upt_prodDescpt;
// Populate textarea for updating product info
const editProd_view = (response) => {
let prod_id = response.id;
let edit_name = response.name;
let edit_price = response.price;
let edit_descpt = response.description;
let prod_idUpt = (document.querySelector("#prod_idUpt").innerHTML = prod_id);
let new_name = (document.querySelector(
"#editProdName"
).innerHTML = edit_name);
let new_price = (document.querySelector(
"#editProdPrice"
).innerHTML = edit_price);
let new_textarea = (document.querySelector(
"#editProdDescpt"
).innerHTML = edit_descpt);
id = prod_id;
// Submitting the form to update product info.
const edit_prod = (document.querySelector(
"#editProd_form").onsubmit = async () => {
try {
// Retrieve values from textarea for content update.
upt_prodName = document.getElementById("editProdName").value;
new_prodPrice = document.getElementById("editProdPrice").value;
new_prodDescpt = document.getElementById("editProdDescpt").value;
const res = await fetch(
`/editProduct/${id}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": getCookie("csrftoken"),
},
body: JSON.stringify({
name: upt_prodName,
description: upt_prodDescpt,
price: upt_prodPrice,
}),
})
.then((res) => res.json())
.then((result) => {
console.log("result ->", result);
});
} catch (err) {
console.error("err", err);
}
// Prevent reloading once post submission is completed.
edit_prod.handleForm();
return false;
});
return false;
};