Filling out a form within a webpage fetched through a DOMParser

Creating automation software in JavaScript using TamperMonkey.

The script performs several AJAX requests that retrieve HTML to be parsed with a DOMParser. Is there a way to submit these forms without opening the newly retrieved HTML on the main page?

Answer №1

Absolutely! The process involves retrieving the form from the document body, creating a FormData object with field values, and sending a POST request.

To simplify things, I utilized the Fetch API. You can learn more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API. Additionally, I assumed that credentials are required to be sent from the same origin.

fetch('<GET URL>', {method: "GET", credentials: 'same-origin'})
  .then((response) => (response.text()))
  .then((responseBody) => {
    var html = parseHTML(responseBody);
    var form = html.querySelector('#my-form'); // Assuming this is the form ID
    var formData = new FormData();

    formData.append('someName', 'someValue'); // Field name should correspond to form fields

    postForm(formData)
      .then((response) => (response.text()))
      .then((responseBody) => {
        // Handle response from form submission here
    });
})

function parseHTML(string) {
  var doc = new DOMParser;
  return doc.parseFromString(string, 'text/html').body;
}

function postForm(formData) {
  return fetch('<POST URL>', {
    method: 'POST',
    body: formData,
    credentials: 'same-origin'
  })
}

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 is the best way to access a Python API or local data within the Google Visualization DataTable JavaScript library?

I have been tirelessly working for the past two weeks to figure out how to load a local CSV file into google.visualization.DataTable() or use Ajax to call a Python Flask API that I created. My ultimate goal is to dynamically create a Gantt chart. Here&apo ...

Tips for transferring HTML code to a controller

Currently facing an issue while working with MVC and attempting to store HTML code from a view in a database field. In the JS section of my MVC solution, I have the following code snippet: var data = { id_perizia: $("#id_perizia").val(), pinSessione: $("# ...

Using PHP in conjunction with Ajax to display the result of a clicked item

Is it possible to display the results of clicked queries on a new page without using URLs from the database? I have the code to search autocomplete from MySQL and navigate to a new page upon clicking, but I want to avoid creating multiple HTML files. Any s ...

Maximizing the potential of AFRAME animations: Tips for recycling your animations

Looking to create a unique and irregular animation, similar to the pattern of a waterdrop falling: Drip nothing Drip Drip Drip nothing nothing Is there a method to achieve this effect or loop an extended animation sequence of dripping? ...

Guide on utilizing a variable as a property in the `indexOf` function within a `map` function

I have a method that looks like this: retrieveUniqueValues(param) { var uniqueValues = []; uniqueValues = this.state.DataObjects.map(item => { if (uniqueValues.indexOf(item[param]) === -1) { uniqueValues.push(item[param]) ...

JavaScript - Utilizing jQuery to dynamically add and remove input fields

I have a form where input fields (groups) are added dynamically. Here's a glimpse of the complex form: FIDDLE The error on the console reads: Error: uncaught exception: query function not defined for Select2 s2id_autogen1 With existing fields in t ...

Multiple selection menus within a single module

I am working on a component with multiple dropdown menus. <div v-for="(item, index) in items" :key="index"> <div class="dropdown"> <button @click="showInfo(index)"></button> <div ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...

Tips for accessing an element using a specific identifier with the variable $key

PHP //This is the HTML code for quantity <p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/> JS function function findTotal() { var arr = document.getElementsByName('qty'); // Calc ...

"Encountering an 'Undefined function' error while implementing AJAX in the code

I'm encountering the issue Uncaught ReferenceError: GetLicenceUserList is not defined in the browser console when I utilize the function with $.ajax inside. However, the function works perfectly fine when I invoke it with just an alert("example& ...

Whenever I try to launch my React app using the `npm start` command in my command

After successfully creating a Simple React App and getting the happy hacking message on cmd, I encountered numerous errors when trying to run "npm start" on cmd. Despite multiple attempts at uninstalling and reinstalling node and npm, the issue persists. H ...

Error occurs when using jQuery.ajax on mobile devices such as android or ios

When accessing my website, an ajax request is made to my REST API. It works perfectly on desktop browsers like Chrome, Internet Explorer, and Firefox, as well as on my Windows phone. However, when trying to access it from an Android or iOS device, the XHR ...

Tips for organizing and concealing images within a Div for seamless transitions (no need for floats)

Currently, I am working on a grid layout for my website. My goal is to have 9 images load quickly, and then once the page has loaded, I want to fetch additional images, insert them into the image containers, and animate between them. While I understand how ...

The placeholder feature seems to be malfunctioning when it comes to entering phone numbers in a react

I am working on a MUI phone number form field. I want the placeholder to show up initially, but disappear when the user starts typing. How can I achieve this functionality in my code? import React from "react"; import MuiPhoneNumber from " ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

Resetting the state of toggle/click states in AJAX and jQuery

Currently, I am encountering a small dilemma with a .on function and AJAX in conjunction with a mobile menu. The mobile menu is located in the header of a site that relies heavily on AJAX for its content loading. This poses an issue because when an AJAX ca ...

Is it possible to generate a PagedListPager without the need to invoke a function?

Managing a list with ajax calls has been fairly smooth on the initial load. The search button triggers an ajax call that loads the first page of results without issues. However, an obstacle arises when trying to implement PagedListPager which ends up reset ...

NodeJS hit with ECONNREFUSED error while trying to run localhost server

I currently have a NodeJS server running on my local machine, listening to port 50000. I am trying to make a simple GET request to this server from another local server, but I keep receiving an ECONNREFUSED error message: { Error: connect ECONNREFUSED 127 ...

What is the process for modifying information within a text document?

What I am trying to achieve is a ticker with two buttons that can increment or decrement the value by one each time they are clicked. In addition, I want this value to be synced with a number stored in a text file. For instance, if both the counter and t ...

Using JavaScript, retrieve the ID of a child element by utilizing details about the parent element

I have implemented a JavaScript function that creates a div element. Within this div, there are multiple checkboxes as child elements. My goal is to use a loop to extract the ids of all these checkboxes. The div has been assigned to a variable named: o ...