Guide on how to transmit JavaScript FormData

Attempting to extract data using FormData

AJAX request on the JavaScript side

function sendForm()
{
  let form=document.getElementById("myForm");

    var formData = new FormData(); 

    for(var i=0; i<form.length; i++)
    {
       formData.append(form[i].name, form[i].value);
    }
    var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function()
        {
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {
                   console.log(xmlHttp.responseText)
            }
        }
        xmlHttp.open("post", url); 
       xmlHttp.setRequestHeader("Content-Type", "multipart/form-data");
       xmlHttp.send(formData); 
 }

Handling in Go side

func login(w http.ResponseWriter, r *http.Request) {
        r.ParseForm()

        username:= r.FormValue("username")     // Data from the form
        password:= r.FormValue("password") 
        fmt.Println(username,password) //getting empty
    }

Even though I tried using the form-data option in Postman, I encountered the same issue. However, it works fine in PHP. In Go lang, I am unsure how to handle multipart/form-data.

Answer №1

xmlHttp.setRequestHeader("Content-Type", "multipart/form-data");

By default, XMLHttpRequest will interpret the FormData object and automatically create the Content-Type header based on its contents.

In this case, you have manually defined the Content-Type header without including the essential boundary parameter, which is necessary for properly decoding the multipart body.

To resolve this issue, it is recommended to remove the specified line of code.

Answer №2

Everything is working smoothly on my end, make sure to double check the network/response. I would recommend utilizing the fetch method as it offers a simpler solution.

function handleSubmit(event) {
  event.preventDefault();

  const formData = new FormData(event.target);

  fetch('https://httpbin.org/post', {
      method: 'post',
      body: formData,
  })
  .then(response => response.json())
  .then(response => console.log(response))
}

document.querySelector('form').addEventListener('submit', handleSubmit);
<form class="form">
  <input type="text" name="name" placeholder="Name" />
  <input type="email" name="email" placeholder="Email" />
  <button type="submit">Submit</button>
</form>

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

Establishing a socket connection within a routing function

I am in the process of organizing my express node app by consolidating all socket.io functionality within express routes or router pages (based on a solution found here: Nodejs include socket.io in router page). Strangely, despite my efforts, I cannot esta ...

Appreciation on Soundcloud

I am attempting to load my SoundCloud likes (formerly known as favorites), but I am facing issues with the ajax query not returning any results. The specific URL I am trying to load is: function retrieveSoundCloudTrackData(linkUrl) { var apiUrl = co ...

My AJAX checkbox change event is not functioning, what could be causing this issue?

This is a sample of the code I'm working with: <form asp-action="Save" asp-controller="ClassesHeld" method="post"> <input asp-for="ClassHeldId" value="@Model.ClassHeldId" hidden /> <div class="form-group"> ...

Jasmine node mistakenly reports "0 tests" even though tests do exist

Something seems off. I was expecting it to show "1 test," but instead, it's showing "0 tests." Any thoughts on why this might be happening? This issue is occurring on OS X. $ jasmine-node --verbose my.spec.js undefined Finished in 0.001 seconds 0 te ...

Analyzing component variable using Jasmine testing

When using spyOn in a jasmine test to monitor a function call from a service that returns an Observable, I encountered the error "unexpected token U JSON." This error originated from this line within the component: this.config = JSON.parse(localStorage.g ...

Loading will continue until the webpage has finished loading

I want to incorporate a loading animation into my webpage that will be displayed until all elements have finished loading. I attempted to create a popup alert using JavaScript <script type="text/javascript> window.onload = function() { a ...

I'm having an issue where I'm trying to post form data using AJAX, but for some reason, the form continues to submit and refresh the page. Can anyone

Recently, I have been working on a small and simple chat application using mainly JQuery and AJAX technologies. Below is the HTML form I have created for this chat application: <form class="chat_form" method="post" id="chat_form" autocomplete="off"> ...

Static variable storing instances of objects

I am faced with the following scenario: function Configuration() { } Configuration.users = { 'user1': new User() } The users variable is a static member of Configuration and I am attempting to have it store an instance of a User object. Howev ...

What strategies can be used to transfer data from the client side to the server side in Next.js version 13

In my current project using Next.js v13, I am facing an issue with client-side and server-side interaction. There is an API that provides the data I need. Initially, I fetched the data from this API by sending a request to the server-side of my application ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...

Webpack attempts to duplicate files prior to compilation but I am anticipating the opposite outcome

I needed the copy plugin to run after compilation, which seemed like the logical order. However, I found myself having to compile using webpack twice every time in order to get the fresh version on production. It wasn't until later that I realized it ...

In what way do Tumblr and Google+ creatively arrange images like a jigsaw puzzle?

I'm interested in creating a unique gallery of images and I'm curious about how to stack them similar to Google and Tumblr. What I mean is, on an archive page of Tumblr, the images are stacked in columns like this: However, I also want the imag ...

The code encountered an error: "execute is not defined."

Whenever I click the execute button, I encounter an error in my console stating "Uncaught ReferenceError: execute is not defined". During onclickng, I am dynamically creating an input box and a button. <!DOCTYPE html> <html lang="en=US"& ...

Transform JSON data into a JavaScript object

There is a JSON string in a specific format: [{"A":"SomeStringData","B":1}, {"A":"SomeStringData","B":2}, ... ... ...] It should be noted that this JSON string passes through all online parsers successfully and is considered valid. An attempt is being ...

Encountering an Illegal invocation error when utilizing Jquery

Encountered an error while attempting to use ajax call in Jquery. See below for an explanation of the issue. Error: Uncaught TypeError: Illegal invocation at e (http://oditek.in/fyndspace/js/jquery.js:4:23990) at Vc (http://oditek.in/fyndspace/js/ ...

Error: The method specified in $validator.methods[method] does not exist

Having trouble solving a problem, despite looking at examples and reading posts about the method. The error I'm encountering is: TypeError: $.validator.methods[method] is undefined Below that, it shows: result = $.validator.methods[method].call( t ...

Implementing Shader Effects around Mouse using Three.js

Could someone please share tips on how to add a shader effect around the mouse area using Three.js? I'm inspired by the homepage of this website: I'm eager to explore some leads or examples. Thank you in advance! ...

The implementation of a generic function interface in Typescript can pose a challenge

I've been working on incorporating a generic function interface, but I'm facing some challenges in getting it to function properly. IToken.ts export interface IToken { token: string; expires: number; } ITokenMapper.ts export interface ...

When a user connects to Node.js using sockets, the previous messages are loaded. However, a bug causes the messages to be loaded to all chat users, instead of just the

New to node.js, I am currently creating a chat application with two main files: server.js (server side) and script.js (client side). In the server.js file: socket.on('previousMessages', function (data){ db.query("SELECT * FROM messages", f ...

Troubleshooting problems with background-image in CSS using Javascript

My latest project involves coding to assign background images to various classes using jQuery. The image files are named in a numerical order, such as 0bg.jpg, 1bg.jpg, 2bg.jpg, and so on. for (i=0; i < 8; i++) { $('.hpCarousel:eq('+i+' ...