Sending a POST request using the XMLHttpRequest object

I am currently developing a back-end API that is connected to a front-end interface in order to create a simulation of a worm moving up and down in a hole (just a test). However, I am facing difficulties in making a POST request to the API from a form while utilizing Bootstrap.

Here is my form:

<div>
    <h2>Insert data for movement</h2>
    <form method="POST" action="localhost:3000/move/data" role="form" id="dataForm">
        <div class="form-group">
            <label for="holeSize">Length:</label>
            <input type="number" class="form-control"  id="holeSize" value="20"/>
        </div>
        <div>
            <label for="moveForward">Forward:</label>
            <input type="number" class="form-control" id="moveForward" value="5"/>
        </div>
        <div>
            <label for="moveBackward">Backward:</label>
            <input type="number" class="form-control" id="moveBackward" value="3"/>
        </div>
    </form>
    <button type="submit" class="btn btn-primary" onclick="sendData()">Start</button>
    <button type="reset" class="btn btn-primary" onclick="reset()">Reset</button>
</div>

Additionally, here is my move.js file:


const form = document.getElementById("dataForm");

form.addEventListener("submit", function (event) {
    event.preventDefault();

    sendData();
})

function sendData() {
    console.log('start')
    document.getElementById('worm').style.top = "300px";

    const XHR = new XMLHttpRequest();

    const FD = new FormData(form);


    XHR.addEventListener("load", function (event) {
        alert(event.target.responseText);
    });

    XHR.addEventListener("error", function (event) {
        alert('Oops! Something went wrong');
    });

    XHR.open("POST", "http://localhost:3000/move/data");

    XHR.send(FD);

}

I added the line "document.getElementById('worm').style.top = "300px";" to test if the button click is functioning properly. The DIV does move on the screen (transition is working), but no POST request is being sent.

Update -> Following a suggestion, I placed the move.js script at the end of my HTML file, and then it started to work as intended.

However, the form data is not being retained. I included the following code:


let movement = req.body;
console.log(movement);

but it simply returns an empty object {}

Answer №1

After moving the position of my header to the bottom of my body and incorporating this code into my custom-express.js file:

    let upload  = multer();

    app.use(cors());
// for parsing application/json
    app.use(express.json());

// for parsing application/x-www-form-urlencoded
    app.use(express.urlencoded({ extended: true }));

// for parsing multipart/form-data
    app.use(upload.array());
    app.use(express.static('public'));

the post function started working smoothly.

Grateful for the helpful tips provided by everyone.

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

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

Mobile Drag and Drop with JavaScript

While experimenting with a user interface I created, I utilized jQuery UI's draggable, droppable, and sortable features. However, I observed that the drag and drop functionality does not work in mobile browsers. It seems like events are triggered diff ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...

"React-pdf throws an error stating that `Buffer` is not defined

I am encountering an issue while trying to utilize the react-pdf library to create pdf files. Upon attempting this, I am facing the following error: BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no ...

for each and every object, execute the asynchronous function

I have a scenario where I need to loop through objects, call an async method ("search") with a callback, and then write the results (resultSet) to a JSON file once all objects are processed. The issue I'm facing is that the writeFile function is execu ...

Issue with PrimeNG Calendar not updating date value within modal

While using the PrimeNG Calendar control, I encountered an issue. Even though I am able to select and store dates, when I try to fetch dates from a database and update the Modal, I receive the following error message: https://i.sstatic.net/LWSUF.png <p ...

I'm facing issues with the angular-stl-model-viewer in my current Angular project

I recently attempted to incorporate an stl-viewer into my Angular project using the npm package angular-stl-model-viewer and managed to install all necessary dependencies without any issues. However, I encountered a problem where the viewer is not displayi ...

How to Arrange AppBar Elements in Material UI with React

I'm struggling to align the CloseIcon to be at the end of the container using flex-end but I can't seem to locate where to apply that style. import React from 'react'; import { makeStyles, useTheme } from '@material-ui/core/sty ...

What is the best way to display a PDF in a web browser using a JavaScript byte array?

I have a controller that sends the response Entity as a byte array in PDF form to an ajax call. However, I am struggling to display it in the browser despite trying various suggestions from old Stack Overflow questions. Here is the response from the Sprin ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

Troubleshooting Problems with Angular Directive Parameters

I'm currently working on a directive that will receive arguments from the HTML and use them to fill in the template fields. Here's the code for the directive: (function(){ angular.module("MyApp",{}) .directive("myDirective",function(){ ...

Issues with AngularJS functionality have been noticed in Chrome browsers on both Mac and Windows platforms, with Safari being

As I begin my journey into learning AngularJS, I encountered an unusual issue. The code snippet below is taken from an online tutorial on Github. Interestingly, the code functions flawlessly on Safari (MAC) but fails to load on Chrome. The same problem p ...

The double click feature is not functioning properly when used in conjunction with the selectpicker Boostrap

<select class= "selectpicker" id="cus_id"> <option value="654" >test1</option> <option value="6877" >test2</option> <option value="8687" >test3</option> </select ...

How to retrieve URL parameters from within the when() function in AngularJS

Consider the code snippet below: $routeProvider.when('/movies/:type', { title: 'Movies', templateUrl: 'pages/movies/movies.html', controller: 'MoviesCtrl' }); Is there a way to retriev ...

Abbreviating Column Labels in Google Visualization

Is there a way to use the google visualization API to display column headers in an abbreviated form in a table, but show the full labels in a pie chart using the same dataset? Check out this snippet of JavaScript: //create the dashboard and table chart ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

Using AngularJS ng-repeat with jQuery find yields a single element result

I'm in the process of developing my very first AngularJS application, and I've run into an issue with the jQuery find function. Essentially, what I'm attempting to do is utilize a custom HTML component that contains a list of buttons generat ...

Add information to the Database seamlessly without the need to refresh the page using PHP in combination with JQuery

Check out my code below: <form action='insert.php' method='post' id='myform'> <input type='hidden' name='tmdb_id'/> <button id='insert'>Insert</button> <p i ...

Is it possible to implement a route within a controller in Express.js?

In my controller, I currently have the following code: module.exports.validateToken = (req, res, next) => { const token = req.cookies.jwt; //console.log(token); if (!token) { return res.sendStatus(403); } try { const ...

Leveraging JavaScript along with the jQuery library and API to showcase information related to

Hey there! I have been working on this API that shows upcoming concerts, but I'm struggling to display the images associated with each concert. I've tried using for loops to iterate through the objects, and it seems like every sixth element has ...