Send data using Javascript without having to refresh the page

As I work on submitting a form in JavaScript, the AJAX feature is functioning perfectly when manually submitting the form. However, there seems to be an issue when JavaScript attempts to submit it, resulting in a refresh.

The current code snippet I am working with looks like this:

:javascript
  wistiaEmbed = Wistia.embed("#{@chapter.video_id}", {
    autoPlay: true,
    videoFoam: true,
    playerColor: 'E68482'
  });
  wistiaEmbed.bind("end", function () {
    document.getElementById('target').style.display = 'none';
    document.getElementById('finished').style.display = 'block';
    document.getElementById('new_chapter_completion').submit();
  });

In addition, here is a preview of my form structure:

= form_for current_user.chapter_completions.build, remote: true, authenticity_token: true do |f|
 = hidden_field_tag :chapter_id, @chapter.id
 = f.submit

I have identified that the main problem lies within the .submit(); method being used. Can anyone guide me on what alternative approach I should consider?

Moreover, I am interested in having the form data submitted by JavaScript without the need for the form to be visibly present. Is there a way to achieve this while still maintaining the required #id?

Answer №1

Your response was:

The form works perfectly when manually submitted

I assume manual submission means clicking on the submit button, correct?

If that's the case, why not try this solution?

In HTML:

<form id="new_chapter_completion">
<!-- input fields go here -->
<input type="submit" value="Submit" id="submit-btn">
</form>

In JS (using JQuery, although it can be done without it):

$(document).ready(function() {
    // your code here, but instead of
    // document.getElementById('new_chapter_completion').submit();
    // you would do this:
    $('#submit-btn').trigger('click'); // simulating a real click
});

Additionally, I prefer for the form to be discreetly hidden

Hiding elements usually involves CSS techniques. There are various methods. For instance, you can make the main wrapper DIV of your page (CSS):

position:relative;
z-index:10;

and place your form within this wrapper (#new_chapter_completion):

position:absolute;
left:0;
top:0;
z-index:1;

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

Utilizing Bootstrap Modal to trigger an Action Result function when a button is clicked

I could use some assistance. In my current setup, I have a file picker that loads a file into a specific table in my database. When the user clicks a button, a bootstrap modal pops up to ask if they are uploading more files. This is how it looks in my vi ...

An interesting result from using fs.appendFile: the mysterious [object Object]

When utilizing console.log, the output of req.query (request.query) appears correct as { name: 'sean', comments: 'Hey' }. However, the issue arises when attempting to write this data to a file using fs.appendFile, as it ends up being wr ...

making changes to the JS node dependency package results in a syntax error during compilation process, particularly within the npm/Vue.js environment

After creating a Js library and encountering stability issues and a few bugs that need fixing, the dilemma of developing a library arises when HMR does not work with dependencies. Here's a possible solution: To start, create a new Vue project using ...

Verify that the user visits the URL in next.js

I need to ensure that a function only runs the first time a user visits a page, but not on subsequent visits. For example: When a user first opens the HOME page, a specific condition must be met. When they then visit the /about page, the condition for th ...

Is there a way for me to manage the rendering of a three.js scene?

I've noticed that most examples use a loop structure to render the scene, like so: renderer.render(scene, camera); function render(){ renderer.render(scene, camera); //code for rendering requestAnimationFrame(render); } render(); Howev ...

Ways to completely eliminate a global component in VueJS

I have a unique component named button-widget that has been globally registered. Vue.component('button-widget', { template: `<button>My Button</button>` }) Now, I am wondering how I can permanently delete this component. I do ...

Ways to substitute the $(document).ready function?

I'm facing a problem and struggling to find a solution. Here is the JavaScript script that's causing me trouble: $(function () { $.ajaxSetup({ cache: false }); var timer = window.setTimeout(function () { $(".alert").fadeTo(10 ...

Accessing a JSON key using a JavaScript variable

Is there a way to dynamically replace the key "Argentina" in a JSON object with a javascript variable string? jQuery(document).ready(function() { $.getJSON('countries.json', function(data) { var output= data.Argentina[0].countryPho ...

Tips on preventing duplicate websocket clients in VueJS

Each time I access a component, it triggers the socket.on event. Additionally, there is a Vuejs button component as shown below. So when I emit to the 'socket.on('voice')' event in nodejs, the nodejs socket emits to the 'socket.on( ...

Attempting to include a navigation bar within the footer section of my layout page - the master page on my website

Is there a way to add a navigation bar in my footer on the layout page without having to add it to every individual page? I want the icon color for the active page to be red, but only apply this to the current page and not all pages. Currently, when I nav ...

The issue arising where the callback function fails to execute after making an AJAX POST request

Within my function, I have an AJAX call that I want to make reusable. When the AJAX call is successful, I need to callback a function. var ajaxPostCall = function(data , url ,callback){ // Return the $.ajax promise $.ajax({ data: data, dataType: ...

After refreshing the page in Next JS, there is a delay in loading the Swiper Js styles. The Swiper slides appear stretched while waiting for Next JS to load the styles. Any suggestions

Having an issue with my Next 14.0.3 app and tailwind CSS. I recently installed swiper JS version 11.0.5 using npm. The problem arises when I reload the page, it takes about 1 or 2 seconds for the swiper styles to load. During this time, the swiper slides s ...

Is it possible to create a jQuery-powered color picker that changes colors in real-time

I am currently working on a form that needs to send data to the database. The form includes fields for the product name and specifications details such as spec name and color selection. While I was able to generate the spec input without any issues, I enco ...

Recalling the position of the uploaded image within a v-for loop

I am struggling to solve this issue. Currently, I am utilizing Vue.js in an attempt to construct a dashboard where users can upload up to five images of visitors who are authorized to access a specific service provided by the user. Below is the code snip ...

Verifying whether an item shows potential for being a successful function

When using protractor.js, I am working with functions that utilize promises/defer. For instance: var myFunc = function(_params) { var deferred = protractor.promise.defer(); /***do some magic code***/ /****wait for other promises****/ /*****deferr ...

Bring in Angular module from the npm package

Seeking to integrate the detect-mobile package (https://github.com/hgoebl/mobile-detect.js/tree/v1.4.4) into my Angular application. However, facing challenges with the import process. I've attempted the following methods: import { MobileDetect } fr ...

Using Node.js to parse XLSX files and generate JSON output

Recently, I came across an extremely well-documented node_module known as js-xlsx Curious: How can I convert xlsx to json format? This is the structure of the excel sheet: The desired json output should resemble the following: [ { "id": 1, "H ...

Utilizing NPM Package Configuration Variables with Docker Commands: A Guide

I have a unique file structure where my package.json contains a single variable called settings which defines the port for the application: package.json ... "settings":{ "port": "3000" }, ... In addition, I've set up a custom script to execute a ...

When integrating react-hook-form with Material-UI TextField in a form, an error occurs stating that "TypeError: e.target is undefined" when

Hey there, I stumbled upon something fascinating and could really use some assistance. Every time I attempt to perform an onChange, I run into the following error: TypeError: e.target is undefined. Here's a snippet of my setup: import React, { useE ...

Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receiv ...