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

JavaScript Promise Handling: using fetch method to retrieve and extract the PromiseValue

I am currently struggling to access the [[PromiseValue]] of a Promise. However, my function is returning a Promise instead and what I really want myFunction to return is the value stored in [[PromiseValue]] of the promised returned. The current situation ...

React Native - Implementing a dynamic form that adapts based on the answer given by its parent

My JavaScript Object has a simple state structure as follows: pertanyaan: [{ label: "label1", type: 'dropdown', key: 'keyFoo1', option: [{ value: "foo1" }, { value: "foo2", additional ...

Input field in a tableview

I have a ListView that features a dropdown, 4 textboxes and buttons. My goal is to only show the fourth textbox (enclosed in a span) when the dropdown value in each row of the ListView is set to 2. For instance, if there are 5 records being displayed in t ...

Utilize CSS to showcase the full-size version of a clicked thumbnail

I am working on a web page that features three thumbnails displayed on the side. When one of these thumbnails is clicked, the full-size image should appear in the center of the page with accompanying text below it. Additionally, I have already implemented ...

retrieve Excel document via POST request

I have a scenario where my API endpoint accepts JSON input and returns an Excel file directly instead of providing a link to download the file. How can I use JQuery AJAX to download this file? Here is the backend code snippet: public function postExcel() ...

Pull JSON data from an Ajax application and cycle through the JSON values in a separate function

As I delve into the world of Ajax, I find myself grappling with a particular issue - the feasibility. My current endeavor involves fetching data from a db.json file using Ajax. { "transactions": [ { "date": "4/3/2021", "description": "Electric bill", ...

Executing a complex xpath using Java Script Executor in Selenium WebDriver

When working with a large grid and trying to find an element using XPath, I encountered some difficulties. The XPath used was: By.xpath("//div[contains(text(),'" +EnteredCompetitionName+ "')]/preceding- sibling::div[contains(concat(' &apo ...

Is there a way to configure eslint to recognize and allow the nullish-coalescing assignment syntax?

The "nullish-coalescing assignment" operator, ??=, has been around for some time now in JavaScript. However, it appears that even newer versions of eslint, like 8.38.0, do not seem to recognize it and throw a syntax error regarding the assignment ...

Unique calculation for rotational movement

I am currently developing a unique compass application. Although the project is progressing well, I am facing a significant challenge with one aspect: My code calculates degree angles within the range of -360 and 360: -318°, -29°, 223°, -163°, ... ...

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

Unraveling in jQuery

Struggling to properly handle the data being returned by JQuery from an API call. Currently encountering an error in the process. Is it possible to iterate through data using a JQuery loop like this? $.each(data.results, function (i, item) { // attemptin ...

The mysterious anomaly in Vue.js

I am attempting to assign a data object named types upon receiving a response in the ready() method. This is what I have: export default { data () { return { types: null } }, ready () { TypeService.showAll(1) .then(functio ...

Show only specific items in an AngularJS application

As a newcomer to AngularJS and the Ionic framework, I'm currently working with the basic Starter Tabs Ionic template. I would like to implement a "Favourite/Bookmark" feature for certain items and display them on a separate tab. The structure of my b ...

What is the best way to verify the presence of a file using jQuery?

I am using "tinyMCE" dynamically on a single page. To modify the content in "tinyMCE", I have to use the "setContent" function. However, I am unsure how to check for the existence of a file (using PHP's is_file function) either within ajax or before ...

Linking Google Form Data to a MongoDB Database

Looking to integrate Google form with mongodb for data collection. Need help setting it up using NodeJs. Any advice on how to approach this? ...

Display Default Image in Vue.js/Nuxt.js when Image Not Found

I'm currently working on implementing a default image (placeholder image) for situations where the desired image resource is not found (404 error). I have a dictionary called article which contains a value under the key author_image. Although the stri ...

Error Alert: Request missing connection details while trying to connect to Sql server via express.js

I am currently utilizing the most recent versions of node, express, and mssql module. My objective is to establish a connection with the local instance of SQL Server 2014 through express.js. Following the guidelines provided in the official documentation, ...

The login page continues to show an error message for incorrect credentials unless the submit button is clicked

My current project involves a React component called "Signin.js". Within this component, there are login input fields as I am working on creating a login system using Node.js, Express.js, and MySQL. To achieve this, I have set up a post request that sends ...

How to Remove onFocus Warning in React TypeScript with Clear Input Type="number" and Start without a Default Value

Is there a way to either clear an HTML input field of a previous set number when onFocus is triggered or start with an empty field? When salary: null is set in the constructor, a warning appears on page load: Warning: The value prop on input should not ...

Retrieve the public URL from the index.html file following the build process

In my project, I utilized ReactJS by creating an app with the command npx create-react-app my-app. To build the project, I used yarn build. Within the package.json file, the scripts section appears as follows: "scripts": { "start": "react-scripts sta ...