Error occurred when attempting to send a POST request to the server using AJAX and data did

When I try to send form data using a POST request via AJAX, I am encountering an issue. The data being sent seems complete when I console it in the AJAX call, but on the server side, parts of the object appear to be missing and the data is getting cut off. It's puzzling why there's this discrepancy between what was sent and what was received.

Here is some relevant HTML for the form section:

<form method='POST' action='/' id='submitText' enctype="multipart/form-data">
    <textarea name='csv' id='text' form='submitCSV'></textarea>
    <br>
    <button type='submit'>Convert to CSV</button>
</form>

This is my AJAX call:

$(document).ready(function () {
    //your code here
    $('#submitText').on('submit', event => {
        event.preventDefault();
        let formData = $('#submitText :input').val();
 
        $.ajax({
            url: 'http://localhost:3000/',
            type: 'POST',
            data: formData,
            processData: false,
        })
        .done(() => {
            console.log('successful');
        })
        .fail(() => {
            console.log('failed');
        })
    });
});

This is the formData being displayed in the AJAX code:

{
    "firstName": "Joshie",
    "lastName": "Wyattson",
    "county": "San Mateo",
    "city": "San Mateo",
    "role": "Broker",
    "sales": 1000000,
    "children": [
        {
            "firstName": "Beth Jr.",
            "lastName": "Johnson",
            "county": "San Mateo",
            "city": "Pacifica",
            "role": "Manager",
            "sales": 2900000,
            "children": [
                {
                    "firstName": "Smitty",
                    "lastName": "Won",
                    "county": "San Mateo",
                    "city": "Redwood City",
                    "role": "Sales Person",
                    "sales": 4800000,
                    "children": []
                },
                {
                    "firstName": "Allen",
                    "lastName": "Price",
                    "county": "San Mateo",
                    "city": "Burlingame",
                    "role": "Sales Person",
                    "sales": 2500000,
                    "children": []
                }
            ]
        },
        {
            "firstName": "Beth",
            "lastName": "Johnson",
            "county": "San Francisco",
            "city": "San Francisco",
            "role": "Broker/Sales Person",
            "sales": 7500000,
            "children": []
        }
    ]
}

On the server side (using express) this is the relevant code for that POST route:

app.post('/', (req, res) => {
    console.log(req.body);
    res.end();
})

Here is how req.body appears when consoling it out:

{
    '{\n    "firstName": "Joshie"\n   ,\n    "lastName": "Wyattson",\n    
    "county": "Sateo",\n   
    "role": "Broker",\n  
    "sales": 1000000,\n    
    "children": [\n    
        {\ateo",\n    
        "role": "Broker",\n     
        "sales": 1000000,\n      
        "children": [\n      
            {\
             ca",\n          
            "role": "Manager",\n      
            "sales": 2900000,\n      
            "chilca",\n            
            {\n              
            firstName": 
            "Smitty",\n           
            "lastName": "Won",\n         
            "county": "San Mateo",\n        
            "city": "Redwood City",\n       
            "role": "Sales Person",\n      
            "sales": 4800000,\n          
            "children": ': [ '' 
  ]

I'm unsure if the issue lies with how I'm sending the data to the server or how I'm receiving it on the server side. Any insights would be appreciated.

Answer №1

When using $.ajax, it's important to note that the default content type is x-www-form-urlencoded, but in your case you're sending JSON data. Therefore, make sure to set the correct content type.

    $.ajax({
        url: 'http://localhost:3000/',
        type: 'POST',
        data: jsonFormData,
        contentType: 'application/json'
    })

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

Match all routes except `/api/login/` using Regular Expressions

Currently, I am working on some authentication tasks within Express: router.post( '*', expressJwt({ secret: config.SECRET, getToken: function fromHeaderOrQuerystring(req) { if (req.cookies.sessionUniversalCook ...

Execute a PHP class method using AJAX

Here is an example of what I am trying to achieve: class testing { function execute(){ perform action; } } I am looking to use ajax to determine if a specific button has been clicked: echo "<button name=\"updateList\" type=\"butto ...

Track the amount of time visitors spend on my website with the help of AJAX

Looking for assistance with my Ajax script. I'm trying to track and record the amount of time a visitor spends on my website, then send that data to a PHP page: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">< ...

Issue with React App in production: Unable to locate routes

I have built a fullstack application using Create-React-App for the frontend and Express.js for the backend. To connect my development setup, where CRA runs on port 3000 and the backend on port 5000, I utilize CRA's proxies to forward specific routes ...

When attempting to access the callback response with HTML tags from the server, the AJAX request in jQuery fails

I am currently facing a challenge while working on an ajax form submission that returns Json response. Everything functions smoothly except for a specific situation where I need to include HTML content in the response, such as a URL link for users to acces ...

When executing store.sync() in ExtJS, all fields are passed

In the latest version of ExtJS (6.5.0), I have set up a Store and an editable grid panel: Ext.define('StateStore',{ extend: 'Ext.data.Store', alias: 'store.stateStore', storeId : 'StateStore', field ...

What is the best way to send an object array from an express function to be displayed on the frontend?

//search.js file import axios from "axios"; export function storeInput(input, callback) { //input = document.getElementById("a").value; let result = []; console.log(input); if (!callback) return; axios.post("ht ...

The dropdown button becomes unresponsive when attempting to navigate within it using ajax requests

Hello fellow members of the StackOverFlow community, I recently implemented a Bootstrap 5 dropdown button to fetch tabs from the backend using AJAX. Everything was functioning correctly until I encountered an issue where, upon clicking a button within one ...

Save a randomly generated string in the Session, which will be replaced when accessed through a different PHP file

I have created a form with a hidden input field, and its value is dynamically set using a function. <?php class Token { public static function generate(){ return $_SESSION['token'] = base64_encode(openssl_random_pseudo ...

The significance of API Input Validation and Steering Clear of Lengthy Conditional Statements

Currently, I am working on ensuring that my API functions correctly even in cases of bad or missing data. At the moment, I have an if statement that checks for any missing inputs. If an input is missing, it returns false, otherwise there is a large else b ...

Tips for generating numerous queries within one GET request

Can I use node-pg to execute multiple queries in a single GET request? For instance, if I have code that looks like this: const getSomeInfo = (request, response) => { pool.query('SELECT * FROM jobs', (error, results) => { ...

Having issues with your Node application that uses Express and Body Parser for handling POST requests? Let me help you troub

I'm facing an issue with my app posts and I initially thought it was due to bodyParser. Despite trying various combinations from online sources, the problem persists. Even the ...res.send("Something")... function is not functional. Can anyone provide ...

Calculate and retrieve the result from the event handling function

I need to capture a returned value and store it in a variable within an event handler function. Below is a sample code snippet demonstrating this: var xhr = new XMLHttpRequest(); function getData(e) { if (xhr.readyState === 4) { if (xhr.s ...

Issue with API showing return value as a single value instead of an array

My database consists of collections for Teachers and Classes. In order to fully understand my issue, it's important to grasp the structure of my database: const TeacherSchema = new Schema( { name: { type: String, required: true } ...

The HTML required attribute seems to be ineffective when using AJAX for form submission

Having trouble with HTML required attribute when using AJAX submission I have set the input field in a model Form to require attribute, but it doesn't seem to work with ajax. <div class="modal fade hide" id="ajax-book-model" a ...

URL not passing on variable

Here is the code I have for a basic 'change email' script. I'm currently struggling to get it working and can't figure out what's wrong. <?php if (isset($_GET['u'])) { $u = $_GET['u']; } if (isset($_POS ...

Running promises in sequence with Node.js

Hey there, I'm looking for a way to run promises sequentially in Node.js. In the example below, I am looping through an array of hours and want to fetch results from the database for each hour in the same order as they were retrieved. angular.forEac ...

My goal is to develop a custom forEach function that retrieves a substring from each element in an array

I have a file containing image names like: sciFi.png, posed.png, birdA.png, dolphin.png, horse.png, shake.png, loft.png, basement.png, avenger.png, friend.png In my JavaScript document, I am trying to read this file and convert it into an array. Then, I w ...

ExpressJs routing is throwing a "404 Not Found" error when attempting to

I am relatively new to using Express, and I have set up a route for accessing a single record using the ObjectID from MongoDB (/report/:id). However, when I try to open the route, it displays "Cannot get /report/ObjectID". The code in the router file is as ...

NextJs/Express Server Encounters Domain HTTPS Request Error

Yesterday, I successfully deployed my website on a VPS. Everything was working fine on the VPS IP until I installed certbot on my domain. Unfortunately, I encountered the following error: Mixed Content: The page at 'https://mydomain.com/' was loa ...