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

The function to save a mongoose schema is not valid

I encountered an issue with the StripeToken.save function while using the code snippet below. After double-checking my model, I can't seem to pinpoint what went wrong. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var s ...

Placing an exit button beside an image for easy navigation

Here is a snippet of my code: <style type="text/css"> .containerdiv { position:relative;width:100%;display:inline-block;} .image1 { position: absolute; top: 20px; left: 10px; } </style> <div class="containerdiv"> <ima ...

Combine the first name and last name in the where clause of a Laravel MongoDB query for searching

Having trouble concatenating first name and last name in Laravel while using MongoDB. The SQL query I tried isn't working: ->orWhere(\DB::raw("CONCAT(`last_name`, ' ', `first_name`)"), 'LIKE', "%".$searc ...

What are some strategies for optimizing React performance when managing controlled input from numerous components?

Building a Parent component with multiple child components, each passing data to the parent for an API call. The structure is as follows: const MainComponent = () => { const [child1input, setChild1Input] = useState(""); const [child2input, setChild ...

Unleashing the potential of Chrome's desktop notifications

After spending the past hour, I finally found out why I am unable to make a call without a click event: window.webkitNotifications.requestPermission(); I am aware that it works with a click event, but is there any way to trigger a Chrome desktop notifica ...

Checking for multiple click events in jQuery

To access the complete code, visit the GitHub Pages link provided below: Link This is how the HTML code appears: <ul class="deck"> <li class="card"> <i class="fa fa-diamond"></i> </li> ...

jQuery Show/Hide Not Working Properly

I'm attempting to showcase one Tweet at a time and have it rotate through different tweets. I'm facing an issue where it works correctly on one type of page, but not on the other. Could this be due to a CSS precedence rule overriding the function ...

Altering styles of a child component within a parent component using material-ui

I am trying to customize the appearance of a child component from within the parent component Let's take a look at the child component, MyButton.js: import ButtonComponent from '@material-ui/core/Button' const useStyles = makeStyle((theme) ...

Issue with generating random cells in a table using a loop

Within my HTML code, I have a table constructed using the table element. To achieve the goal of randomly selecting specific cells from this table, I implemented a JavaScript function that utilizes a for loop for iteration purposes. Despite setting the loop ...

Validating Cognito credentials on the server-side using Node.js

I am currently developing server-side login code for AWS Cognito. My main goal is to verify the existence of a user logging into the identity pool and retrieve the attributes associated with them. With email login, everything is running smoothly using the ...

Request to api.upcitemdb.com endpoint encountering CORS issue

This code may seem simple, but for some reason, it's not working as expected. What I'm trying to achieve is to call the GET API at: I want to make this API call using either JavaScript or jQuery. I've attempted various approaches, but none ...

Searching for data across multiple tables using the Laravel framework combined with Vue.js and API integration

I am currently implementing a multi-search feature for a single table The search functionality is functioning correctly but only for one column Here is the snippet from my controller: public function index() { return Matter::when(request('sear ...

Tips for refreshing only a portion of a webpage using JavaScript/jQuery

I have two distinct navigational sections on my website. The left column has its own navigation menu, while the right column (main content area) contains a separate set of links: My goal is to click on a link in the left-hand sidebar (such as "Resume", "E ...

Transferring previously obtained data to templateProvider within AngularJS

I'm currently working with AngularJS 1.3 and UI-Router. I have a state set up with a resolve and a templateProvider. My goal is to utilize the data fetched from the database in the resolve within the templateProvider without having to make duplicate ...

What methods can be used to control access to document.styleSheets data, and what is the purpose behind doing so?

Recently, I came across the document.styleSheets API, which allows you to access stylesheets used by a website. Using this API is simple, for example, document.styleSheets[0].cssRules will provide all CSS rules for the first stylesheet on a page. When I t ...

Unable to fetch information from Grid to a new window with Form in Extjs 4

Having trouble transferring data from a grid to a form in Extjs 4. I'm attempting to pass the field vid to the form for testing purposes, but I'm unable to do so. Despite trying several examples and ideas, I can't seem to make it work. The ...

Guide on utilizing the h function in Vue3 for seamless binding and passing of properties and events from parent to child components

Utilizing Vue3 and naive ui for front-end development has been a challenge for me as I primarily focus on back-end development and lack expertise in front-end technologies. To enhance user interaction, I incorporated naive ui’s BasicTable along with an ...

Incorporate the block-input feature from sanity.io into your next.js blog for enhanced functionality

Currently, I'm in the process of creating a blog using next.js with sanity.io platform. However, I am facing some difficulties when it comes to utilizing the code-input plugin. What's working: I have successfully implemented the code component b ...

Looking to save a CSS element as a variable

I am working on improving the readability of my code in Protractor. My goal is to assign a CSS class to a variable and then use that variable within a click method. element.all(by.css("div[ng-click=\"setLocation('report_road')\"]")).cl ...

Transferring information from MySQL to Vue.js data attribute

I have retrieved some data from MySQL and I am looking to integrate it into a vue.js data property for seamless iteration using v-for. What is the ideal format to use (JSON or array) and how can I ensure that the data is properly accessible in vue.js? &l ...