Send data using only Javascript

Hey there, I'm a beginner in javascript and I'm having some trouble submitting a form using pure javascript.

Here is my code:

var myform = document.getElementById('js-post-form');
myform.addEventListener('submit', function(e){
    e.preventDefault();
    var request = new XMLHttpRequest();
    request.open(myform.method, myform.action, true);
    request.setRequestHeader('X-CSRFToken', cookies['csrftoken']);
    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    request.onload = function () {
      if (this.status >= 200 && this.status < 400) {
        console.log("ready");
        var data = JSON.parse(this.response);
        console.log('success');
      } else {
        console.log("not ready yet");
      };
    };
    request.onerror = function() {
      console.log("connection error");
    };
    request.send();
  });

});

Can anyone help me figure out what I'm missing?

Thanks in advance!

Answer №1

You need to make sure you are sending the request body to the server using the send() method. Here's an example:

var myform = document.getElementById('js-post-form');
myform.addEventListener('submit', function(e){
    e.preventDefault();
    var request = new XMLHttpRequest();
    request.open(myform.method, myform.action, true);
    request.setRequestHeader('X-CSRFToken', cookies['csrftoken']);
    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    request.onload = function () {
      if (this.status >= 200 && this.status < 400) {
        console.log("ready");
        var data = JSON.parse(this.response);
        console.log(data); // returns the dictionnary { selected_elements:[] } 
        console.log('success');
      } else {
        console.log("not ready yet");
      };
    };
    request.onerror = function() {
      console.log("connection error");
    };
    request.send(myform); // Make sure to pass the form as the request body.
  });

});

Refer to Mozilla Docs on send() method for more information.

Answer №2

After struggling for a while, I found the solution by using FormData. Huge thanks to Nalin for guiding me in the right direction!

Here is the JavaScript code snippet that helped me:

var myform = document.getElementById('js-post-form');
myform.addEventListener('submit', function(e){
    var formData = new FormData(myform);
    e.preventDefault();
    var request = new XMLHttpRequest();
    request.open(myform.method, myform.action, true);
    request.setRequestHeader('X-CSRFToken', cookies['csrftoken']);
    request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    request.onload = function () {
      if (this.status >= 200 && this.status < 400) {
        console.log("Request successful");
        var data = JSON.parse(this.response);
        console.log(data); // Displaying { selected_elements:[] } 
        console.log('Success');
      } else {
        console.log("Request not successful");
      };
    };
    request.onerror = function() {
      console.log("Connection error");
    };
    request.send(formData);
  });

});

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

Developing a TypeScript NodeJS module

I've been working on creating a Node module using TypeScript, and here is my progress so far: MysqlMapper.ts export class MysqlMapper{ private _config: Mysql.IConnectionConfig; private openConnection(): Mysql.IConnection{ ... } ...

The issue of passing state in React Router v4 Redirect unresolved

I have a specific private route, /something, that I only want to be accessible when logged in. I've used Redirect with the state parameter set, however, when I try to access it at the destination, location.state is showing as undefined. Here is how I ...

Retrieve the modal ID when the anchor tag is clicked in order to open the modal using PHP

I am facing an issue with opening a modal and passing the id value using JavaScript. The id value is shown in a hidden input field. <a href="#modal2" data-toggle="modal" data-id="<?php echo $CRow['id'];?>" id="<?php echo $CRow[& ...

Control the contents of the DOM using JavaScript in a single-page application

Is there a way to append a div element with p and h3 tags after the <product-list> component in Angular? When I try putting it inside window.onload(), it only works when the page is reloaded or refreshed. This approach doesn't work well in singl ...

Verifying user identity in Django Rest Framework by integrating with Google Authentication

When implementing JWT authentication using username/password, the process goes as follows: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer '''The POST request appears like this: <QueryDict: { 'csrfmid ...

Reducing the amount of code within an if statement by utilizing JavaScript

I just finished coding a solution: if(!fs.existSync(path.join(data,file,path)){ fs.mkdirSync(path.join(data,file,path)); } if(!fs.existSync(path.join(another,file)){ fs.mkdirSync(path.join(another,file)); } if(!fs.existSync(path.join(new,file,temp,pa ...

Utilizing outdated database with master data in Django

I have a database in one project that contains information about employees which I need to access in another project. Specifically, I have a user for whom I need to assign a job title from the other project's database. To do this, I set up my project ...

Generate the Xpath for the mentioned href element to use with Selenium Webdriver

I need help creating the Xpath for a specific href element using Selenium webdriver with only IE browser. The HTML code I am working with is as follows: I am looking to find the Xpath for: . Can someone assist in generating the correct Xpath expression ...

Update and republish an outdated npm package

After successfully publishing an npm package, I attempted to make an update which unfortunately resulted in some issues. It seems that I made a mistake during the build process. Since it had been a year since my last update, I have forgotten the exact step ...

The styles from the npm package are not being properly applied to the class

After creating my react npm package using webpack, I encountered an issue where the styles from the package were not being applied to classes when installed in my react project. I used style-loader in my webpack configuration, but kept getting errors sayin ...

Refresh gif without having to reload it in Internet Explorer 11

I'm attempting to create a feature where a gif restarts when clicked by the user, without needing to reload it (due to the heavy size of the gif which is preloaded for my application). The current code functions flawlessly on Chrome and other "modern ...

Baconjs exclusively retrieves the final debounce value

Below is a code snippet that showcases my current implementation: let watcher; const streamWatcher = bacon.fromBinder(sink => { watcher = chokidar.watch(root, { ignored: /(^|[\/\\])\../ }); watcher.on('all&a ...

Tips for correctly storing an async/await axios response in a variable

I am facing a challenge with the third-party API as it can only handle one query string at a time. To overcome this limitation, I am attempting to split multiple strings into an array, iterate through them, and make async/await axios calls to push each res ...

Tips for Passing Parameters to Vuex mapActions correctly:Executing mapActions in Vuex requires a specific

I am facing an issue with my ProjectPage.vue where I display project issues in a v-data-table. The projects are fetched from a server API call in the sidebar and displayed there. Once I select a project, I want to use its id to retrieve its corresponding i ...

An in-depth guide on implementing debounce functionality for `keyup` events in Vue.js

I am attempting to detect when the user begins typing and stops typing using the debounce function. I experimented with Lodash and Underscore.js. On my textArea v-on:keyup="handler($event)" handler: function(e) { ...

Unable to toggle Bootstrap 5 tabs in a Nunjucks template - the issue persists

I have been following the bootstrap documentation for tabs which can be found at this link After referencing the documentation, I replicated the sample implementation in my code as shown below: --- title: Portfolio description: Portfolio --- {% exten ...

What is the best way to transform an Object into an Array?

[ { id: '5b3a223296fb381a29cf6fd9', number: 1, name: 'Tablet White EliteBook Revolve 810 G2', dprice: '0', image: '' } ] This message is generated by the angular application. Upon inspecting its type, it was identi ...

What is the most efficient way to organize an array by date?

Here is the data I have: const data = [{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44}, {date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53}, {date: "2022-05 ...

Am I on the right track with my service definition in Angular?

(function(){ angular.module('myApp',[]) })(); (function(){ angular.module('myApp.dashboard',[]) })(); (function(){ angular.module('myApp.value',[]) })(); (function(){ 'use strict'; angular.modu ...

Utilizing HTML documents instead of images in Owl Carousel 2

I am currently utilizing owl carousel 2 to construct a basic sliding carousel. However, I am only using images at the moment and would like to incorporate HTML files instead. These HTML files contain multiple divs where images can be inserted, and instead ...