why javascript-ajax submitting form multiple times - javascript

I am doing single page app. If i type something on form and click the submit button then it sends one request. Second time if i type something and click it sends two requests. Third time it sends three requests and so on. Why is this? Did i do any mistake in javascript code?
here is my html
function reply_mail(idi) {
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'none';
document.querySelector('#reply-view').style.display = 'block';
fetch(`/emails/${idi}`)
.then(response => response.json())
.then(email => {
// Print email
var strp = `${email.subject}`;
var ini = 'Re: '
document.querySelector('#reply-recipients').value = `${email.sender}`;
if (strp.slice(0, 4) == 'Re: ') {
document.querySelector('#reply-subject').value = `${strp}`;
} else {
document.querySelector('#reply-subject').value = ini.concat("", strp);
}
var output = `On ${email.timestamp} ${email.sender} wrote:|
${email.body} |
`;
// ... do something else with email ...
document.querySelector('#reply-body').value = output;
// ... do something else with email ...
console.log(email);
});
document.querySelector('#reply-submit').addEventListener('click', function(event) {
event.preventDefault();
rec = document.querySelector('#reply-recipients').value;
sub = document.querySelector('#reply-subject').value;
bod = document.querySelector('#reply-body').value;
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: rec,
subject: sub,
body: bod
})
})
.then(response => response.json())
.then(result => {
// Print result
if ('error' in result) {
console.log(result);
document.querySelector('#reply-error').style.display = 'block';
document.querySelector('#reply-error-i').innerHTML = `<p>${result['error']}</p>`;
} else {
console.log(result);
document.querySelector('#reply-error').style.display = 'none';
load_mailbox('sent');
}
});
})
}
```
<div id="reply-view">
<h3>New Email</h3>
<div class="alert alert-danger" role="alert" id="reply-error">
<div id="reply-error-i">
</div>
</div>
<form id="reply-form">
<div class="form-group">
From: <input disabled class="form-control" value="soham#example.com">
</div>
<div class="form-group">
To: <input id="reply-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="reply-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="reply-body" placeholder="Body"></textarea>
<input type="submit" id="reply-submit" class="btn btn-primary" />
</form>
</div>

Related

When I type or backspace fast the for loop runs more than once. Even if i backspace to an empty string it still runs, why and how do i fix it?

Its a form page to create a list of anime. You can use a search bar to find anime to select. As user types it loads up to 20 potential matching anime found by the Jikan Api v4. Currently if I type fast the fetch call/loop runs more than once and I have more than 20 anime appended to container when there should only be 20 at a time. Also if i backspace to fast it happens, as well as when you backspace all out and there's only an empty string it still shows animes
<% layout('layouts/boilerplateBodyOnly') %>
<form action="/profile/<%=user._id%>" method="POST" novalidate class="validated-form" enctype="multipart/form-data">
<div class="row listForm">
<nav id="sidebarMenu" class="col-4 d-md-block sidebar collapse pt-0">
<div class="position-sticky">
<h1 class="text-center listHeader">New AnimeList</h1>
<div class="mb-3 px-3">
<label class="form-label" for="title">Title</label>
<input class="form-control" type="text" name="animeLists[title]" id="title" required />
<div class="valid-feedback">Looks Good!</div>
</div>
<div class="mb-3 px-3">
<label class="form-label">Choose Anime(s)</label>
<input class="form-control" type="search" id="animeSearch" name="anime" placeholder="Search for anime" required search-input />
</div>
<div class="mb-3 px-3">
<button class="btn btn-success">Create List</button>
</div>
All AnimeLists
</div>
</nav>
<div class="col-8 ms-sm-auto">
<h2 class="text-center">Click to add</h2>
<div class="row animes px-3 pt-3 ms-auto" data-animes-container></div>
<template search-template>
<div class="col-auto searchList d-flex align-items-end px-0 mx-1 mb-2">
<input type="checkbox" id="animeCheckbox" name="" data-input />
<label for="animeCheckbox" class="searchResults d-flex align-items-end" data-label><span class="p-2" data-title></span></label>
</div>
</template>
</div>
</div>
</form>
<script>
const searchTemplate = document.querySelector('[search-template]');
const animeContainer = document.querySelector('[data-animes-container]');
const searchInput = document.querySelector('[search-input]');
searchInput.addEventListener('input', e => {
animeContainer.innerHTML = '';
const value = e.target.value.toLowerCase();
if (value.trim().length === 0) {
console.log('empty');
return;
} else {
console.log(value);
fetch(`https://api.jikan.moe/v4/anime?order_by=favorites&sort=desc&sfw=true&q=${value}`)
.then(res => res.json())
.then(data => {
let anime = data.data;
console.log('hello');
for (let i = 0; i < 20; i++) {
const animeRes = searchTemplate.content.cloneNode(true).children[0];
const title = animeRes.querySelector('[data-title]');
const label = animeRes.querySelector('[data-label]');
const input = animeRes.querySelector('[data-input]');
label.setAttribute('for', `animeCheckbox${i}`);
input.setAttribute('name', `animeCheckbox${i}`);
input.id = `animeCheckbox${i}`;
label.style.backgroundImage = `url(${anime[i].images.jpg.large_image_url})`;
title.innerText = anime[i].title;
animeContainer.append(animeRes);
}
})
.catch(function (error) {
// handle error
console.log(error);
});
}
});
</script>
here you go bro
let timer; // Timer identifier
const waitTime = 500; // Wait time in milliseconds
// Search function
const search = value => {
animeContainer.innerHTML = '';
if (value.trim().length === 0) {
console.log('empty');
return;
} else {
console.log(value);
fetch(`https://api.jikan.moe/v4/anime?order_by=favorites&sort=desc&sfw=true&q=${value}`)
.then(res => res.json())
.then(data => {
let anime = data.data;
console.log('hello');
for (let i = 0; i < 20; i++) {
const animeRes = searchTemplate.content.cloneNode(true).children[0];
const title = animeRes.querySelector('[data-title]');
const label = animeRes.querySelector('[data-label]');
const input = animeRes.querySelector('[data-input]');
label.setAttribute('for', `animeCheckbox${i}`);
input.setAttribute('name', `animeCheckbox${i}`);
input.id = `animeCheckbox${i}`;
label.style.backgroundImage = `url(${anime[i].images.jpg.large_image_url})`;
title.innerText = anime[i].title;
animeContainer.append(animeRes);
}
})
.catch(function (error) {
// handle error
console.log(error);
});
}
// TODO: Make HTTP Request HERE
};
// Listen for `keyup` event
searchInput.addEventListener('keyup', e => {
const value = e.target.value.toLowerCase();
// Clear timer
clearTimeout(timer);
// Wait for X ms and then process the request
timer = setTimeout(() => {
search(value);
}, waitTime);
});

JavaScript code wont execute but get printed as part of html

I have this html code with js inside and every time i submit the js wont execute but get printed as html, saw many similar problems on stack overflow they said something about not closing <div> correctly but i cant find the error on my code
This is my html code:
<div class="container-fluid">
<div class="row" id="riparues_frm">
<form method="post" action="ruajRiparues.php" id="FormaRuaj_rp" enctype="multipart/form-data">
<input type="hidden" name="idRiparues" id="idRiparues" />
<div class="form-group row d-flex" style="margin-bottom: 20px;" >
<div class="col-sm-4">
<input type="button" class="btn btn-outline-info" value="Kerko skript sipas pershkrimit" onclick="lookUpBox({
title: 'Kerko skript sipas pershkrimit',
url: 'kerkoSkript_sipas_emrit.php?chars=',
onItemSelected: function(data){
$('input[id=' +
'idRiparues]').val(data.idRiparues);
$('#delref').attr('href','fshi_riparues.php?id=' + data.idRiparues);
$('input[name=kodi]').val(data.kodi);
$('input[name=seq]').val(data.sequenca);
$('input[name=pershkrimi]').val(data.pershkrimi);
$('#scripti').val(data.script);
$('#scripti').load(data.script, resizeArea);
$('#modelScripti').val(data.modelScript);
$('#modelScripti').load(data.modelScript, resizeArea);
$('#dataregj').val(data.datazgjedh);
$('#tipi').val(data.Tipi);
//kosta070622 start
var checkTipi = data.Tipi;
**filter()**
//kosta070622 end
},
tableHeader: ['idRiparues','kodi', 'pershkrimi','sequenca','script','modelScript','data']
})
" />&nbsp
</div>
and this is my js code:
<script>
function filter() {
if(isadmin === 1){
if(checkTipi != 'S' && checkTipi != 'B'){
document.getElementById('modelScripti').hidden = true;
document.getElementById('pathi').hidden = false;
document.getElementById('myfile').hidden = false;
document.getElementById('seq').disabled = true;
document.getElementById('lblpershkrimi').innerHTML = 'Emri Skedarit';
document.getElementById('lblscript').innerHTML = 'Pathi Relativ';
document.getElementById('lblmodelscript').innerHTML = 'Model Pathi Relativ';
$('#pathi').val(data.modelScript);
}else{
document.getElementById('modelScripti').hidden = false;
document.getElementById('pathi').hidden = true;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = false;
document.getElementById('lblpershkrimi').innerHTML = 'Pershkrimi';
document.getElementById('lblscript').innerHTML = 'Script';
document.getElementById('lblmodelscript').innerHTML = 'Model Script';
}
}else{
if(checkTipi != 'S' && checkTipi != 'B'){
document.getElementById('modelScripti').hidden = true;
document.getElementById('pathi').hidden = false;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = true;
document.getElementById('pathi').disabled = true;
document.getElementById('scripti').disabled = true;
document.getElementById('Edito').disabled = true;
document.getElementById('lblpershkrimi').innerHTML = 'Emri Skedarit';
document.getElementById('lblscript').innerHTML = 'Pathi Relativ';
document.getElementById('lblmodelscript').innerHTML = 'Model Pathi Relativ';
$('#pathi').val(data.modelScript);
}else{
document.getElementById('modelScripti').hidden = false;
document.getElementById('pathi').hidden = true;
document.getElementById('myfile').hidden = true;
document.getElementById('seq').disabled = false;
document.getElementById('scripti').disabled = false;
document.getElementById('Edito').disabled = false;
document.getElementById('lblpershkrimi').innerHTML = 'Pershkrimi';
document.getElementById('lblscript').innerHTML = 'Script';
document.getElementById('lblmodelscript').innerHTML = 'Model Script';
}
}
console.log(Boolean(isadmin));
console.log("HYRI KETU");
}
</script>
The html code it was written by someone else i just added the function filter and thats the the code that is being printed as html on the website.
I think that you are missing 3 div closing tags, and that is why your script is being read as html.
//1<div class="container-fluid">
//2<div class="row" id="riparues_frm">
<form method="post" action="ruajRiparues.php" id="FormaRuaj_rp" enctype="multipart/form-data">
<input type="hidden" name="idRiparues" id="idRiparues" />
//3 <div class="form-group row d-flex" style="margin-bottom: 20px;" >
//4 <div class="col-sm-4">
<input type="button" class="btn btn-outline-info" value="Kerko skript sipas pershkrimit" onclick="lookUpBox({
title: 'Kerko skript sipas pershkrimit',
url: 'kerkoSkript_sipas_emrit.php?chars=',
onItemSelected: function(data){
$('input[id=' +
'idRiparues]').val(data.idRiparues);
$('#delref').attr('href','fshi_riparues.php?id=' + data.idRiparues);
$('input[name=kodi]').val(data.kodi);
$('input[name=seq]').val(data.sequenca);
$('input[name=pershkrimi]').val(data.pershkrimi);
$('#scripti').val(data.script);
$('#scripti').load(data.script, resizeArea);
$('#modelScripti').val(data.modelScript);
$('#modelScripti').load(data.modelScript, resizeArea);
$('#dataregj').val(data.datazgjedh);
$('#tipi').val(data.Tipi);
//kosta070622 start
var checkTipi = data.Tipi;
filter()
//kosta070622 end
},
tableHeader: ['idRiparues','kodi', 'pershkrimi','sequenca','script','modelScript','data']
})
" />&nbsp
//1 </div>
//2 </div> //this and below are added by me
//3</form>
//4 </div>
//5 </div>

How to add image into axios data

I would like to add an image into Axios data and send the data to .Net Controller. I have never done this before with an image and I need help.
The image source it's not coming from input, but from img tag.
Any idea how to insert the image into a JSON object(data)?
Thank you in advance!
function PostOffer(){
let localhost = "https://localhost:7009";
let url = localhost + "/Client/New";
let formClientName = document.getElementById("offer-client-name").value;
let formClientEmail = document.getElementById("offer-client-email").value;
let formClientPhone = document.getElementById("offer-client-phone").value;
let formClientDate = document.getElementById("offer-client-date").value;
let formClientTotal = document.getElementById("main-calculator-total-amount-final").innerText;
if(parseFloat(formClientTotal) > 0){
if(formClientName.trim() != "" && formClientEmail.trim() != "" && formClientPhone.trim() != "" && formClientDate.trim() != ""){
let data = {
clientName : formClientName,
clientEmail : formClientEmail,
clientOfferDate : formClientDate,
clientPhone : formClientPhone,
clientTotal : formClientTotal,
};
axios.post(url, data)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
ClearOfferSend();
}else{
document.getElementById("validation-inputs-send-offer").style.display = "flex";
}
}else{
document.getElementById("validation-inputs-send-offer").style.display = "flex";
document.getElementById("validation-inputs-send-offer").innerText = "Total amount can not be 0";
}
}
<div class="final-form">
<input type="text" asp-for="Name" id="offer-client-name" placeholder="name" required/>
<input type="email" asp-for="Email" id="offer-client-email" placeholder="email" required/>
<input type="text" asp-for="Phone" id="offer-client-phone" placeholder="phone" required/>
<label for="DateOffer">When do you want to start the project?</label>
<input type="date" asp-for="DateOffer" id="offer-client-date" placeholder="date" required/>
<div class="row">
<button class="btn-close-final-offer" onclick="CloseOfferForm();">Close</button>
<button class="btn-send-final-offer" onclick="PostOffer();">Send</button>
</div>
<span id="validation-inputs-send-offer">Inputs can not be empty!</span>
</div>
.NET controller:
[HttpPost]
public IActionResult New([FromBody] ClientAxiosModel offersend)
{
if (ModelState.IsValid)
{
_clientService.Create(offersend.clientName, offersend.clientEmail, offersend.clientPhone, offersend.clientOfferDate, offersend.clientTotal);
return Ok();
}
else
{
return NotFound();
}
}
If you use input type="file" you can insert image into axios with the following code:
<!-- HTML code -->
<input type="file" id="uploadImage" name="image">
// JS code
let formDataImage = document.getElementById("uploadImage").files[0];
// Add in data object too
data.image = formDataImage;

How to remove unwanted element

I'm trying to write easy validation code and I have trouble. I've created element div '._error-alert' and I cant remove it if the input isn't empty.
When I press submit appears my element '._error-alert' but it doesnt disapear when I try to type something there. I'll be very grateful if u help or at least show me the other path to solve it
const form = document.querySelector('.validation__form'),
reqItems = document.querySelectorAll('._req'),
emailTest = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+[^<>()\.,;:\s#\"]{2,})$/,
onlyTextTest = /^[a-zA-Z0-9#]+$/,
onlyNums = /^[0-9]+$/;
const inputTest = (example, input) => example.test(input.value);
const formAddError = (input) => {
if (input.classList.contains('_req')) {
const createBlock = document.createElement('div');
createBlock.classList.add('_error-alert');
input.parentElement.insertAdjacentElement("beforeend", createBlock);
createBlock.innerText = `Invalid ${input.getAttribute("name")}!`;
}
input.parentElement.classList.add('_error');
input.classList.add('_error');
};
const formRemoveError = (input) => {
input.parentElement.classList.remove('_error');
input.classList.remove('_error');
};
// validates form if function validateForm didn't have any errors and removes my created elements '._error-alert'
const sendValidatedForm = (e) => {
e.preventDefault();
let error = validateForm(form);
if (error === 0) {
console.log('fine');
form.reset();
document.querySelectorAll('._error-alert').forEach((errorAlert) => {
errorAlert.remove();
});
}
};
form.addEventListener('submit', sendValidatedForm);
// there I want to check input and remove '._error-alert' if input isnt wrong
const checkInput = () => {
reqItems.forEach((reqInput, index) => {
reqInput.addEventListener('input', () => {
formRemoveError(reqInput);
});
});
};
checkInput();
const validateForm = (form) => {
let error = 0;
reqItems.forEach(reqInput => {
reqInput.value.trim();
formRemoveError(reqInput);
if (reqInput.getAttribute("name") == "email") {
if (!inputTest(emailTest, reqInput)) {
formAddError(reqInput);
error++;
}
} else if (reqInput.getAttribute("name") == "phone") {
if (!inputTest(onlyNums, reqInput) && reqInput.value.length < 8) {
formAddError(reqInput);
error++;
}
} else if (reqInput.getAttribute("name") == "name") {
if (!inputTest(onlyTextTest, reqInput)) {
formAddError(reqInput);
error++;
}
}
});
console.log(error);
return error;
};
<form action="" class="validation__form">
<div class="validation__input-list">
<div class="validation__input-item">
<input type="text" class="validation__input-input _req" name="name" placeholder="Name">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input" name="surname" placeholder="Surname">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input _req" name="phone" placeholder="Phone">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input _req" name="email" placeholder="Email">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input" name="password" placeholder="Password">
</div>
</div>
<button class="validation__form-btn">Submit</button>
</form>
Set the css visibility property of the element to hidden.
const error_element = document.getElementsByClassName('_error-alert')
error_element.style.visibility = 'hidden'

ASP.Net MVC Ajax.BeginForm File Upload Response Issue

So I have a modal which allows a user to upload a file, I am wanting to get a json response back to say whether the upload was successful or not and display that to the end user.
Currently my View is this
#model int
<div id="modal_newSupportPlan" class="modal fade" style="display:none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">x</button>
<h6 class="modal-title">New Support Plan</h6>
</div>
#using (Ajax.BeginForm("CreateSupportPlan", "Client",
new AjaxOptions() { OnSuccess = "getSupportPlanResult", HttpMethod = "post" },
new { #Class = "form-horizontal", enctype = "multipart/form-data" }))
{
<div class="modal-body">
<input name="ClientFK" value="#Model" style="display:none" />
<div class="form-group" id="newsupportplan_error_plantype">
<label class="control-label col-sm-3">Type of Plan</label>
<div class="col-sm-9">
<select id="planType" name="PlanType" class="form-control">
<option></option>
<option value="1">Initial Plan</option>
<option value="2">Pre Employment Plan</option>
<option value="3">6 Month Plan</option>
<option value="4">12 Month Plan</option>
<option value="5">Ongoing Support Plan</option>
</select>
</div>
</div>
<div class="form-group" id="newsupportplan_error_StartDate">
<label class="control-label col-sm-3">Date</label>
<div class="col-sm-9">
<input type="text" class="form-control pickadate-accessibility" name="Date" />
</div>
</div>
<div class="form-group" id="newsuportplan_error_SLILevel">
<label class="control-label col-sm-3">Support Level</label>
<div class="col-sm-9">
<select id="SliLevel" name="SliLevel" class="form-control">
<option></option>
<option value="1">SLI 1</option>
<option value="2">SLI 2</option>
<option value="3">SLI 3</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">Upload File</label>
<div class="col-sm-9">
<input type="file" name="Blob" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
}
</div>
</div>
And my Controller method is this
[HttpPost]
public ActionResult CreateSupportPlan(ModelHelper.SupportPlanViewModel supportPlanDetails)
{
try
{
esp_storage_supportPlans espStorageSupportPlans = new esp_storage_supportPlans();
bool validation = true;
var errorList = new List<string>();
var passList = new List<string>();
if (string.IsNullOrEmpty(supportPlanDetails.PlanType.ToString()))
{
errorList.Add("SupportPlanType");
validation = false;
}
else
{
passList.Add("SupportPlanType");
}
if (string.IsNullOrEmpty(supportPlanDetails.Date.ToString()))
{
errorList.Add("Date");
validation = false;
}
else
{
passList.Add("Date");
}
if (string.IsNullOrEmpty(supportPlanDetails.SliLevel))
{
errorList.Add("SLILevel");
validation = false;
}
else
{
passList.Add("SLILevel");
}
if (supportPlanDetails.Blob != null && supportPlanDetails.Blob.ContentLength > 0)
{
if (validation)
{
var uploadedFile = new byte[supportPlanDetails.Blob.InputStream.Length];
supportPlanDetails.Blob.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
espStorageSupportPlans.Blob = uploadedFile;
espStorageSupportPlans.ClientFK = supportPlanDetails.ClientFK;
espStorageSupportPlans.Date = Convert.ToDateTime(supportPlanDetails.Date);
espStorageSupportPlans.SliLevel = supportPlanDetails.SliLevel;
if (supportPlanDetails.PlanType == 1) espStorageSupportPlans.PlanType = "Initial Plan";
if (supportPlanDetails.PlanType == 2) espStorageSupportPlans.PlanType = "Pre Employment Plan";
if (supportPlanDetails.PlanType == 3) espStorageSupportPlans.PlanType = "6 Month Plan";
if (supportPlanDetails.PlanType == 4) espStorageSupportPlans.PlanType = "12 Month Plan";
if (supportPlanDetails.PlanType == 5) espStorageSupportPlans.PlanType = "Ongoing Support Plan";
string extension = Path.GetExtension(supportPlanDetails.Blob.FileName);
espStorageSupportPlans.Extn = extension;
espStorageSupportPlans.FileName = supportPlanDetails.Blob.FileName;
db.esp_storage_supportPlans.Add(espStorageSupportPlans);
db.SaveChanges();
}
}
else
{
errorList.Add("Blob");
validation = false;
}
if (!validation)
{
return Json(new { result = "Validation", errors = errorList, pass = passList }, JsonRequestBehavior.AllowGet);
}
return Json(new { result = "success" }, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(new { result = "failed" }, JsonRequestBehavior.AllowGet);
}
}
My javascript is the following 2 parts
first part has made the form work by uploading the file
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
My second part is the onsuccess function but this is not being triggered. And stopped triggering when I implemented the first part to get the form uploading
function getSupportPlanResult(data) {
console.log("here");
if (data.result === "success") {
opts.title = "Completed";
type: "success";
opts.text = "Support Plan created successfully.";
opts.type = "success";
new PNotify(opts);
supportPlanTable.destroy();
BuildDataTable_SupportPlan();
$('#modal_newSupportPlan').modal('hide');
} else {
if (data.result === "validation") {
console.log(data);
} else {
opts.title = "Somthing Went Wrong";
opts.text = "Support Plan failed to create, please try again.";
opts.addclass = "stack-custom-bottom bg-danger";
opts.type = "error";
new PNotify(opts);
}
}
}
Why don't you use any library to do the dirty work of handling XHR for you? Like axios? The code could look then something like this:
window.addEventListener("submit", e => {
const form = e.target;
if (form.getAttribute("id") === '<my_unique_id_of_this_element>') {
axios({
method: form.method,
url: form.action,
data: /* whatever payload you need to send */
})
.then(({data}) => getSupportPlanResult(data));
}
});

Categories

Resources