While attempting to create an AJAX request to submit users to an external API, I faced a problem that is hindering my progress. Since I'm more familiar with PHP than JS, I saw this as an opportunity to expand my knowledge in JavaScript.
The approach I took checks if the form contactForm
is filled out completely. If it's not, the script prevents sending the data and displays the next form customerForm
.
If all the fields are properly filled, the script sends the data to the API using AJAX, then hides the current form and shows the next one.
(function() {
'use strict';
window.addEventListener('load', function() {
var contactForm = document.getElementById('contactForm');
var customerForm = document.getElementById('customerForm');
var validation = Array.prototype.filter.call(contactForm, function(form) {
contactForm.addEventListener('submit', function(event) {
if (contactForm.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
contactForm.classList.add('was-validated');
if (contactForm.checkValidity() === true) {
customerForm.style.display = 'block';
contactForm.style.display = 'none';
event.preventDefault();
(function() {
var contactEmail = document.getElementById('contactEmail').value;
var contactResellerId = 2;
var contactName = document.getElementById('contactName').value;
var contactLastName = document.getElementById('contactLastName').value;
var contactCompany = document.getElementById('contactCompany').value;
var contactRegNum = document.getElementById('contactRegNum').value;
$.ajax({
url: url,
type: 'POST',
crossDomain: true,
withCredentials: true,
data: JSON.stringify({
firstname: contactName,
lastname: contactLastName,
company: contactCompany,
email: contactEmail,
reseller_id: contactResellerId,
comregnum: contactRegNum
}),
dataType: 'json',
headers: {
'Authorization': 'Basic '+token,
}
})
.done(function (response) { alert('Contact has been created!'); })
.fail(function (jqXHR, textStatus, errorThrown) { alert(jqXHR); });
})();
}
}, false);
});
}, false);
})();
However, when I try to run this code, I receive the following error message:
The entity is not a well-formed 'application/json' document. Missing or empty input","code":"400"
I confirmed that the form values are correctly captured in the variables by using console.log()
. But what does the error message mean by "missing or empty input"? Did I overlook something?
Thank you in advance for your assistance. Have a great weekend!