The AJAX Request has indicated that the entity provided is not in an accurate 'application/json' format. It seems to be missing or empty, leading to an error with a code of '400'

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!

Answer №1

Figuring out the solution to this issue was surprisingly simple: The problem lay in the incomplete structure of my AJAX request. Here is the corrected version:

$.ajax({
    url: url,
    method: 'POST',      <------- CORRECTED
    crossDomain: true,
    withCredentials: true,
    data: JSON.stringify({
        firstname: contactName,
        lastname: contactLastName,
        company: contactCompany,
        email: contactEmail,
        reseller_id: contactResellerId,
        comregnum: contactRegNum
    }),
    dataType: 'json',
    contentType: 'application/json',   <------ FIXED
    headers: {
        'Authorization': 'Basic ' + token,
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch out the content when the button is clicked

Seeking a code snippet to enable clicking a button (Button labeled "Next") for replacing existing code on the page with new code. Current code below should be replaced, starting from the score counter section. Please excuse any messy code as I'm new a ...

Dynamically add a plugin to jQuery during execution

After installing jQuery and a jQuery-Plugin via npm, I am facing the challenge of using it within an ES6 module. The issue arises from the fact that the plugin documentation only provides instructions for a global installation through the script tag, which ...

Attempting to transform a numerical value into CSS syntax

Currently, I am attempting to loop through several DIV elements, extract a numerical value from each DIV, and then based on that value matching a specific value in the JavaScript code, assign a particular CSS Class back to the original DIV. This is the sn ...

Having trouble with Autocomplete not entering cities into the form?

While experimenting with Google's API, I have encountered confusion regarding why cities like Staten Island, Brooklyn, Queens, and various others are not being placed into the form like other cities. According to Google's API, "locality" is suppo ...

Attempting to extract a text string from a chunk of HTML code

My goal is to extract a text string (specifically, an article title) from a snippet of HTML code. The title in question reads "Journalist Allegedly Spied on Zoom Meetings of Rivals in Hilariously Dumb Ways." The challenge lies in the fact that the title d ...

Using a variable as a key for a JavaScript object literal with a string value

Is there a way to achieve this? objPrefix = btn.attr('data-objprefix'); //<button data-objPrefix="foo"> var sendData = {objPrefix : {"bar":"ccccc"}}; My desired outcome is {"foo" : {"bar":"ccccc"}}; however, the current result shows { ...

Navigating a FormData object in javascript on a .NET WebAPI version 5.2.2

I am currently working on integrating webcam video recording upload using the example provided in this RecordRTC GitHub repo. However, I have encountered a compiling error when trying to use "Request.Files" as indicated in the screenshot below. The error ...

Using Vue.js to process JSON data

My issue lies within this JSON data. I am trying to consume only the first element of the array using Vue.js 2 in order to display it. I was able to achieve this successfully using the console, but not with Vue.js. This line of code in the console works: ...

Automatically Update Woocommerce Checkout with Ajax when Item is Removed or Quantity is Altered

Is there a way to update the checkout page using ajax when an item is removed or when the quantity selector is clicked? The code in my /checkout/order-review.php file does not use the default WooCommerce table. Here is the code snippet: <?php defin ...

What is the best method for extracting attribute values from multiple child elements using puppeteer?

When using this code, I can retrieve the attribute value of the first element selected. By adding /html/body/section/div[3]/img<2> or img<3> in the xpath, I am able to retrieve data for subsequent img elements. However, the parent element on t ...

The process of authenticating route parameters in Nuxt

I'm having trouble validating route parameters in my page component using the following code: async validate({ params, store }) { await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id) } And here's the corresponding code in the store: ...

Refresh the dropdown menu selection to the default option

My HTML dropdown menu includes a default option along with dynamically generated options using ng-options. The variable dropdown is bound to the dynamic options, not the default one. <td> <select ng-model="dropdown" ng-options="item as item.n ...

Adding the API JSON response to the MetaInfo in Vue.js

i am dealing with a meta tag that has the following structure metaInfo () { return { title: 'my title', meta: [ { name: 'description', content: 'my description' }, ...

What is the functionality of the Jenkins job console output?

I am considering incorporating the console output technology from a Jenkins job into one of my applications. It's fascinating how Jenkins jobs constantly display command output in the console with minimal buffer and no page refresh. Could someone expl ...

What is the best way to read a local text file and store its contents in a string variable within a

Within my ReactNative project, I am seeking to retrieve the content of static text files and store it in a string variable. Here is an example of how I would like to achieve this: var content = loadPlainTextFile("resources/tags.txt"); var tags = content.s ...

Developing web applications using AJAX and ASP.NET in Visual Studio 2010

I am currently working on an AJAX project and I am looking for the proper way to implement it, without relying on the built-in AJAX feature of Visual Studio. My approach involves using AJAX calls with jQuery. However, I have encountered a problem. On the ...

Passing data from child to parent in Angular using EventEmitter

I have integrated a child grid component into my Angular application's parent component, and I am facing an issue with emitting data from the child to the parent. Despite using event emitter to transmit the value to the parent, the variable containing ...

Creating dynamic transformations and animations for characters and words within a paragraph in 3D

Looking to add animation effects to specific parts of a paragraph, but transforming the entire box instead. Remembering seeing a solution on StackOverflow before, now regretting not saving it. Spent over an hour searching for a similar answer without succ ...

Remove rows that have values within a specific range

I'm facing an issue in Google Sheets where I'm attempting to delete entire rows on the "Data" sheet if any value in column B matches values from the range D3:E20 in the "Backend" sheet. The code provided works when a word is hardcoded as the cond ...

Retrieve information from child components and populate form fields

Currently, I am working on creating a dynamic form that utilizes a sub component to display input fields because creating them statically would exceed a limit. I pass the states for the form I created along with some data and the change form function. Howe ...