One way to store form data in a database without triggering form submission with socket.io

Question: I am facing a dilemma on how to save form input data to a MySQL database while also using socket.io, as the preventDefault function seems to be causing issues. My current setup involves submitting form data via post requests and then storing it in the database through my express app.

Previously:

**index.ejs**
<form class='form' role='form' action='/users' method='POST'>
  <input class='form-input' name='Client[FName]' type='text' />
  <input class='form-input' name='Client[LName]' type='text' />
  etc..
</form>

**server.js**
router.post('/users', (req, res) => {
  const post = req.body.Client
    pool.query('INSERT INTO Client SET ?', post, (err, result) => {
     res.redirect(`users/${result.insertId}`);
  })
})

The introduction of socket.io for real-time updates caused me to have to prevent default form submission:

**index.js**
let form = document.querySelector('.form');
let inputs = document.querySelectorAll('input');

form.addEventListener('submit', (e) => {
  e.preventDefault();
  socket.emit('message', {
    FName: inputs[0].value,
    LName: inputs[1].value,
    etc,
    etc
  })
})

**server.js**
io.on('connection', function(socket) {
 socket.on('message', (message) => {
  socket.broadcast.emit('message', message)

   *sql insert statement here??*

 })
});

The functionality of socket.io is successful in updating the DOM in real time. However, I now need to find a way to resume saving the data to MySQL. Is there an alternative solution to inserting a query into the socket.io function or setting a timeout in the event listener?

I appreciate your assistance with this matter. Thank you.

Answer №1

There are two possible solutions in this scenario

1) Execute the POST request to /users within server.js upon receiving the client message

2) Perform an ajax POST request to /users from the index.js submit handler as shown below:

form.addEventListener('submit', (e) => {
  e.preventDefault();
  socket.emit('message', {
    FName: inputs[0].value,
    LName: inputs[1].value,
    ...
  });
  $.post({
    url: "/users",
    ...

   });
})

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 could be causing me to receive two responses when submitting via AJAX?

Currently, I am implementing a comment reply system for my blog. The commenting feature works well initially. However, when I click the reply button for the second time, it ends up duplicating my reply on the subsequent comment. Surprisingly, this issue do ...

The json.stringify method is inserting additional backslashes into the response sent by res.send()

My API needs to provide the following data in its response. { users: 'All users are as follows: [{id: 1}, {id: 2}]'} The response should be a JSON object with one key value being a JSON array. However, the JSON array is converted into a string b ...

Mastering Light and Camera Selection in Three.js

Question, In the editor found at this link, you can click on a light or camera to select it. I am familiar with using raycaster.intersectObjects(objects) to select meshes, but how can I achieve the same result for lights and cameras which do not have mesh ...

Word with the Most Points

I have created a code to determine the highest scoring word as a string, however when I calculate all words and attempt to display the results, I am encountering an issue where all results are showing as: NaN function high(x) { var words = x.split(&ap ...

Leverage a JSON variable within jQuery to showcase additional JSON variables

This code snippet is a work in progress, and there is room for improvement. The goal here is to have the content of thumb2 displayed in the #imageLoad container when a user clicks on a thumbnail inside the #placeholder DIV. Keep in mind that both Thumb and ...

What is the method for performing a bulk insertion in mySQL with the assistance of node.js?

What is the best method for performing a bulk insert into a mySQL database when utilizing a tool such as https://github.com/felixge/node-mysql ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

Why am I getting the error "TypeError: Object(...) is not a function" when attempting to integrate Vanilla Tilt with React?

Looking for assistance on implementing Vanilla Tilt in my React application, I have referenced the following example: https://codesandbox.io/s/vanilla-tilt-with-react-n5ptm The code snippet I am working with is as follows: import React, { Component, useEf ...

What causes index.html to be returned instead of app.css?

I deploy my Angular application using an express server. var express = require('express'); var server = express(); server.use(express.static('./app')); server.all('*', function(req, res) { res.sendFile('index.html&apos ...

Looking for the optimal method to display numerous lines of text in HTML, one by one, at intervals of 60 seconds?

I'm working on a display page for my website. The main text in the center needs to change every 60 seconds. I have over 150 individual lines of text that I want to cycle through on the page. What would be the most efficient way to load all these te ...

Avoiding the utilization of automatically generated JSON files as a data source in Rails when

I have implemented javascript code that uses JSON to generate a timeline. The JSON is being created using json_builder and it contains only the current user's information. The JSON displays correctly when accessed directly through its URL, but when th ...

Establishing a fresh JSON upload module

I have this JSON object stored in a file called object.json. Every time the method getAlbum() is called during an HTTP request, the JSON object is cached because it is imported at the top of the page. Is there a way to create a new instance of the object ...

Enhanced SQL Statement

Data Structure Below are the CREATE queries for the two tables: TableA: (key1, key2) create table TableA(key1 varchar(500), key2 varchar(500), primary key(key1)) engine = innodb; For example, key1 = /home/xbox/b.txt key2 = /home/xbox/ T ...

Error: The MySQL connection in Spring Hibernate has been terminated

After much deliberation, I am attempting to execute 32 write operations within a single @Transactional block. The database configuration includes maxActive connections set at "100", maxIdle at "50", maxTimeout at 150000, and removeAbandonedTimeout at 3000. ...

Easily executed GET request results in an issue: 'Failed to cast to ObjectId'

Recently, while conducting backend testing using Postman, I encountered a situation that has left me puzzled. Within my project structure, I have a file named users.js where I define various routes. To integrate these routes into my main application file, ...

Is there a way to customize the animation for a button in material UI?

Trying to implement material UI in React and looking for a button that does not have the standard wave animation effect upon clicking, which you can see demonstrated here. Instead, I am searching for an animation that instantly fills the entire button wit ...

A technique for postponing the addition of a class to a div

I am attempting to create a unique type of slider effect. Inside a single div named #slider, I have 9 items displayed in a line. Link to JsFiddle The slider is 1860px wide, but only 620px is visible at any given time due to the parent having an overflow: ...

Preventing Further Navigation When an Incorrect Password is Entered

I am struggling with preventing navigation when a user enters the wrong password in my app. Despite trying to implement an If condition, the redirection still occurs after catching the error. Here is the code snippet I have been working with: login = (em ...

Continuously refreshing the information displayed in the Angular view that is linked to a function in the TypeScript file whenever a modification is identified

I am currently working on an ecommerce application using the MEAN stack. In order to make the app real-time, I have integrated pusher-js. To show the quantity of a specific item in the shopping cart, I have implemented a function in the ts file that loops ...

Issue 1173575 has been identified in the Chrome bug tracker, indicating that non-JavaScript module files are no longer

Hey there! I'm completely new to the world of web development and currently enrolled in a Udemy bootcamp. While working on my app, everything was going smoothly until my browser suddenly stopped rendering and displayed this error message: VM10:6747 c ...