I am trying to stop the page from refreshing when submitting a form by using this:
window.addEventListener("load", function () {
let settings_form = document.getElementById("settings_form");
// handle form submit
settings_form.addEventListener("submit", function (e) {
e.preventDefault(); // before the code
save_settings();
// Should be triggered on form submit
console.log("hi");
return false;
});
});
But it does not work.
If I comment the save_settings
method the page won't reload. Obviously, I need that method.
function save_settings() {
// let form = document.getElementById("settings_form");
let json_data = toJSONstring(settings_form);
console.log(json_data);
post_data("api/settings/change", json_data).then((send_response) => {
console.log(send_response);
conn_status = 1;
// logs to page
// get_settings() // update interface with newer settings
get_info();
});
}
I don't know which function makes e.preventDefault();
to not work.
For more context:
// parse form data into json
function toJSONstring(form) {
let object = {};
console.log(form);
let formData = new FormData(form);
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if (!Reflect.has(object, key)) {
object[key] = value;
return;
}
if (!Array.isArray(object[key])) {
object[key] = [object[key]];
}
object[key].push(value);
});
console.log(JSON.stringify(object));
return JSON.stringify(object);
}
// send/post json
async function post_data(api_path, json_data) {
let post_url = ROOT_URL + api_path;
const response = await fetch(post_url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: json_data,
});
//check
if (!response.ok) {
conn_status = 0;
const message = `An error has occured: ${response.status}`;
throw new Error(message);
}
return await response.json();
}
<form id="settings_form" class="settings_form">
<label for="wifi_ssid">Change SSID</label>
<input type="text" name="wifi_ssid" id="wifi_ssid" />
<label for="wifi_pass">Change Password</label>
<input type="text" name="wifi_pass" id="wifi_pass" />
<label for="ap_ip">Change IP Address</label>
<input type="text" name="ap_ip" list="ap_ip" />
<datalist id="ap_ip">
<option>192.168.100.20</option>
</datalist>
<input type="button" value="Save Settings" id="submit_btn">
</form>
I have also tried listening to the click
event on the button:
window.addEventListener("load", function () {
let button = document.getElementById("submit_btn");
// handle form submit
button.addEventListener("click", function (e) {
e.preventDefault(); // before the code
save_settings();
// Should be triggered on form submit
console.log("hi");
return false;
});
});
Later Edit:
I am running a local mock-up JSON server in order to test my code.
I've tried the code here: https://jsbin.com/xogozovawe/1/edit?html,js,output and it works.
Might this be the local server's fault ?