I’m working on a Django Python/Javascript project. The PUT request is done through the client and sent back to the server. After sending the request successfully, the page makes a refresh which is causing the exposure of the csrf token middleware in the URL. I already implemented AJAX, returning false, added an event.preventDefault(), passed a cookie through the header of the fetch, used async functions, and added a try and catch syntax. And I can’t figure out why it is not affecting the resubmission. I need to stop the webpage from refreshing once the submission is done so that the csrf_token won't show appended to the URL.
Hopefully, someone can let me know what I’m not seeing here. Thanks!
// Set global variables to use in form submission
var id, upt_prodName, upt_prodPrice, upt_prodDescpt;
// Block to populate textarea that allows the user to update 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;
//On submit, send product info to update the product.
const edit_prod = (document.querySelector(
"#editProd_form").onsubmit = async () => {
try {
// Get all values from textarea to update content.
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);
}
//Once the post has been submitted, return false to prevent reloading.
edit_prod.handleForm();
return false;
});
return false;
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…