What is the equivalent format for sending a FormData POST XHR request as when using a Submit button?

My website has a <form> that is usually submitted using a submit button:

<form action='/doit' method='post'>
<input type='text' name='ex1_q1' value='AAA'>
<input type='text' name='ex2_q1' value='BVB'>
<input type='submit' value='Go'>
</form>

This functionality works as intended.

Now, I want to automatically send the form data every 10 seconds using AJAX without refreshing the page. However, when implementing this:

setInterval(function() {
    var fd = new FormData(document.querySelector('form'));
    fd.append("dt", +new Date);    
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/doit");
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(fd); 
}, 10 * 1000);

The data is sent successfully, but the server receives it in a different format compared to when using the "Submit" button.

Specifically:

  1. With Ajax/XHR, the body of the request looks like:

    b'------WebKitFormBoundaryQb7yIKHLZODhAjqI\r\nContent-Disposition: form-data; name="ex1_q1"\r\n\r\nAAA\r\n------WebK
    
  2. When using the Submit button, I receive:

    b'ex1_q1=AAA&ex2_q1=BVB&accept=on&numero=1'
    

    which is the desired format for all cases.

Question: How can I ensure that data sent with an XHR request follows the same format as when using a Submit button (as described in case 2.)?

Answer №1

When submitting form data, the encoding is determined by the enctype attribute, which can be either "application/x-www-form-urlencoded" or "multipart/form-data".

Data will always be encoded as "multipart/form-data" when using a FormData object.

To encode data as "application/x-www-form-urlencoded", you should utilize a URLSearchParams object.

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

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...

The button's onclick function is failing to save the record in the database

Hello everyone, I am facing an issue with the ONCLICK button functionality. I have written code to save a form to the database. In the image, there are 2 buttons: Save button (type="submit") Save and New button (type="button") The Save button is ...

Mastering SVG Path Coordinates using Pure JavaScript

Is it possible to target and manipulate just one of the coordinate numbers within an SVG path's 'd' attribute using JavaScript? For example, how can I access the number 0 in "L25 0" to increment it for animating the path? function NavHalf ...

Prevent hyperlink redirection based on specific condition using jQuery

Managing a large number of files on my website and looking to implement a download limit for each user. The download link appears as follows: <a class="btn btn-primary" id="download" href="<?php echo $content_url;?>" onclick=”var that=this;_ ...

Trouble getting Bootstrap typeahead to display data from AJAX with PHP and MySQL

I am facing an issue where all the images are displaying data in the backend, but not in the front end. My code doesn't seem to be working. Even though my code is fetching and displaying data in the console and browser network, it's not showing ...

Can JSON values be multiplied together?

Can you assign the value of a key in JSON by using the result of multiplying/adding two variables, values, strings+number, or strings+strings? Is this feasible? For example: { "string": "600*"+40 } ...

When working with ASP.NET MVC, I encountered an unexpected issue where a JSON response was sending me a file instead of

After receiving JSON data, I observed that instead of updating the jQuery accordion, it prompts to save or open a file. Below is my code and controller setup. I have integrated a jQuery modal dialog for editing employee details using a partial view. When c ...

Issue encountered while deploying on vercel: TypeError - Trying to access properties of undefined (specifically 'and')

Encountered this issue during deployment on Vercel. Npm run build did not show any errors. Configuration : "node": "18", "next": "^14.0.0", "next-transpile-modules": "^9.1.0", An error occurred d ...

Ways to display numerous cards on individual Carousel slides using react-bootstrap

Currently, I am utilizing react-bootstrap to handle my data from an API, which is stored in an array called recipes. My challenge lies in attempting to display 3 items on each slide of a Carousel using react-bootstrap. As of now, each item is appearing on ...

Tips for validating user input in AngularJS without using a form tag

Within a popup, I am displaying HTML content that has been copied from another div and shown in the popup. I need to validate this input field to ensure it is required, and display an error message below the input box. <!-- HTML code for changing zip c ...

By utilizing a combination of JavaScript and jQuery, we can dynamically fill interconnected select boxes with data from an

After finding solutions to this particular query, I successfully managed to populate a select box based on the selection made in another select box. (You can see my answer here) This was achieved by retrieving data from an array structure that was generate ...

Exploring click event beyond React Component: Jest + Enzyme Testing

I am looking to create a Jest and Enzyme test for a component that includes an event listener. The purpose of the test is to ensure that when a mousedown event occurs outside of a specific HTML element, a change is triggered (for example, toggling a state ...

Sending a value to a different Ionic page based on a specific condition

Here is the code snippet from my app.js: var app = angular.module('dbpjkApps', ['ionic']) app.controller('kategoriCtrl', function($scope) { $scope.listKat = [ {kat: 'math'}, {kat: 'physics'}, ...

Choosing a nested object within a JavaScript object

Is there a way to select the style contents of an object within another object? The data consists of a json encoded array. In my scenario, I am using data[i].replies and getting 2. How can I access data[i].userstyles instead? It seems to be an object. h ...

Obtaining the 3D point coordinates from UV coordinates on a 3D plane object using Three.js

I am in the process of creating basic data visualizations using Three.js as my tool of choice. I have a series of PlaneGeometry meshes to which I am applying a transparent texture dynamically generated with red squares drawn at varying opacity levels. My g ...

The functionality of Jquery ajax seems to be ineffective within a Phonegap application

The phonegap app I've been working on was functioning perfectly until today, when the Ajax post request suddenly started getting stuck and the success or failure callbacks weren't being triggered. Oddly enough, when I tested it in a browser, ever ...

Unable to send a post request using ajax

Section of Form in home.php <div id='googleForm'> <form> <div class='item'> <label class='label'>Full Name</label> <input class=&apos ...

Exploring plyr and vue.js: utilizing a computed property to fetch video duration

I am currently attempting to load content dynamically based on the duration of a video being displayed. However, I am encountering issues when trying to access the duration property. Could this problem be related to the timing of plyr's appearance wit ...

Issue encountered while retrieving data using an AJAX call in a multi-phase form on Laravel platform

I'm trying to create a multi-step page form within a Laravel application. The goal is to carry over the user-entered values from the 1st phase of the form to the 3rd phase through an AJAX call (triggered when the user clicks submit on the 2nd phase). ...

Please proceed by submitting all radio buttons that have been checked

Seeking assistance with creating a quiz application using the MEAN stack. Once all questions are attempted, there will be a submit button for checking all selected radio buttons - option 1 corresponds to 1, option 2 to 2, and so on. The current structure o ...