Submitting forms through Vanilla JavaScript using AJAX

Can anyone assist me in implementing an AJAX form submission using Vanilla JavaScript instead of jQuery? I have the following jQuery code that needs to be converted:

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('.myForm').addEventListener('submit', function(event) {
    var data = this;
    var xhr = new XMLHttpRequest();
    xhr.open(data.getAttribute('method'), data.getAttribute('action'));
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        // Handle success
      }
    };
    xhr.send(new URLSearchParams(new FormData(data)));
    event.preventDefault();
  });
});

Answer №1

Utilize the native Fetch API for handling AJAX requests and FormData to process form data efficiently.

In addition, consider replacing your jQuery code with event listeners, query selectors, and attribute getters for a more modern approach.

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('.myForm').addEventListener('submit', function (event) {
    var formData = this;
    fetch(formData.getAttribute('action'), {
      method: formData.getAttribute('method'),
      body: new FormData(formData)
    }).then(res=>res.text())
      .then(function (data) {
        
      });
    event.preventDefault();
  });
});

Answer №2

// Event listener for when the document is fully loaded
window.addEventListener('DOMContentLoaded', () => {

    // Select all forms with a specific CSS class
    var forms = document.querySelectorAll('.ajax-form');
    if (forms && forms.length) {
        forms.forEach(form => {

            form.addEventListener('submit', function(evt) {

                // Prevent default form submission behavior
                evt.preventDefault();           
                
                // Fetching data from {url}
                var xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
            
                xhr.addEventListener('readystatechange', function() {
                    if (this.readyState === 4) {
    
                        // Processing fetched data
                        var data = JSON.parse(this.responseText);
                        console.log(data);
                    }
                });
    
                // Get form data
                var data = new FormData(form),
                    method = form.getAttribute('method'),
                    url = form.getAttribute('action');
    
                // Debugging
                console.log({
                    data: data,
                    method: method,
                    url: url
                });
            
                // Sending request using different methods
                xhr.open(method, url);
                xhr.send(data);
            })
        });
    }
});

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

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...

Exploring GatsbyJs: Optimal Strategies for Storing Strings and Text on Static Websites

Currently in the process of building a website using Gatsby JS and Material UI. I'm wondering about the best approach for storing the site content. This website will serve as a promotional platform for a small business. Should I store the text direct ...

The colorbox division refuses to be shown

Having trouble revealing a hidden div within a colorbox upon click I'm stumped on how to make the div visible inside the colorbox The div is currently hidden, but I need it to be shown when displayed in the colorbox <div class="test">test< ...

Pass a variable between popup.js and background.js in a Chrome Extension

Despite finding some answers to similar questions, none of them provide a complete solution. The information in the answers lacks necessary documents that were not included in the original question. My goal is to create a scaffold for Chrome extensions wh ...

I must create text that is transparent against a colorful gradient background

Hey there! I'm seeking help in figuring out how the text on this site is designed. You can take a look at it here. Essentially, what I'm aiming for is to have the text color match the gradient of the background color from the previous div, while ...

Tips for displaying live data in the rows of Element UI's Table

Recently, I've been working with a table that looks like this. <v-table :data="data"> <v-table-column prop="data.attribute" label="Attribute"> </v-table-column> </v-table> Instead of displaying data.attribute in the co ...

Guide on performing an inner-join query in Firestore using NextJS

My Firestore database contains two collections that I need to work with. The 'uid' field in the users collection and the 'createdBy' field in the 'anuncios' collection both store the same string data, linking each 'anunc ...

Retrieve data from JSON using AJAX

I am working with an API that provides JSON data in the following format: [{ "Code": "001", "Name": "xyz", "Members": [{ "FullName": "User1" }] }, { "Code": "002", "Name": "asd", "Members": [{ "FullName": "User2 ...

Make sure to only update the state in useEffect after retrieving the data from the localStorage

Trying to troubleshoot the continuous looping and crashing issue in my app caused by passing variables in the dependency array of the useEffect hook. These variables are state variables from the context provider. The goal is to make the useEffect hook run ...

HeatMap Visualizations Data

I have a HeatMap calendar project () where I am attempting to populate it with dynamic data. My approach involves extracting various dates from a file and converting them into milliseconds in order to create the necessary key-value pair for the calendar. ...

Why isn't my callback working? Can anyone help me figure out what I did wrong?

I'm currently facing an issue while making an asynchronous call to Redis and attempting to utilize a callback to inform async.js about the completion of the query. I am consistently receiving an error message stating "callback is not a function". Can ...

Difficulty in clearing form values/content despite successfully submitting

Whenever I try to submit my form, the reset function doesn't clear it as expected. Can someone please advise me on how to properly clear my form? My HTML, PHP, and JavaScript codes are provided below. HTML code snippet: <form id="main-contact-for ...

The script fails to load under the specified circumstances

Is there a way to load a script only after the user has logged in to the app and when a specific page is finally made visible? I've tried setting the page to display block using an AJAX call, but even after doing so, the script doesn't load as ex ...

Required form fields are a must when utilizing Material-UI Form and React Testing Library

I'm currently working on testing an MUI form using @testing-library/react. The form consists of required fields, and I need to verify this behavior. Here is the structure of the form: <form id='xml-form' onSubmit={handleSubmit}> ...

Exploring the Possibilities of Greensock within Meteor Templates

Attempting to add animation to a div within a Meteor template using TweenLite with the gsop package installed. The template html code: <template name="mainInit"> <div id="teaContainer"> <h1>Tea</h1> </div> </template& ...

Errors always occur when making POST requests in SAPUI5, leading to a 500 Server Error specifically related to OData

Currently diving into the world of SAPUI5 and OData, I am in the process of creating a basic application that showcases employee data in a table. The objective is to add a new employee to the table whose information will be stored in the SAP backend. Whil ...

Adjust the alignment of an expansion panel header to the right using Vuetify

Incorporating the Vuetify expansion panel, I am aiming to align a specific portion of the content within the <div slote="head"></div> to the right, resulting in this desired layout: https://i.sstatic.net/tbOL8.jpg https://i.sstatic.net/22NTS. ...

The b-link component in bootstrap-vue is not displaying the text content or inner HTML as expected

Having trouble retrieving the textContent from a blink element and modifying it. Interestingly, when attempting the same process with a tag or div tag, it works without any issues. <b-link :ref="index" v-b-toggle="`${index}`" @c ...

Transfer information from an HTML document to a Vue application that has been registered

I have a Vue application set up in the following manner: import { createApp } from 'vue'; import RecommendedJobsWidget from './RecommendedJobsWidget.vue' createApp(RecommendedJobsWidget).mount("#recommendedJobsWidgetInstance" ...

Getting duplicate tokens for multiple users while utilizing Firebase messaging

When attempting to acquire a token from firebase, I employ the code snippet provided below: const messaging = firebase.messaging(); messaging.requestPermission() .then(() =>{ return firebase.messaging().getToken(); }).then(token => { s ...