Tips for preventing redirection in Vue 3 composition API with asynchronous requests

I have successfully configured a submission form to send data to my email and add it to a Google sheet using the method described in this GitHub link. The process worked seamlessly for both purposes.

However, I am facing an issue where upon submitting the form, the page redirects to a JSON page which I do not want. I attempted to use the method provided in the repository but it did not resolve the problem. The repository mentions the usage of Ajax, but I am struggling to implement it effectively. Here is a Vue playground showcasing what I aim to achieve: Vue Playground

Answer №1

Include the following code snippet in your HTML:

<form @submit.prevent="submit">
. Remember to define the function submit in your JavaScript file to handle posting the form data using ajax.

Answer №2

For those encountering a similar issue as I did with my page redirecting to a JSON response after form submission, here's how I resolved it:

import { ref, onMounted, nextTick } from 'vue'

onMounted(() => {
  nextTick(() => {
    form.value.addEventListener('submit', handleFormSubmit)
  })
})

function handleFormSubmit(event) {
  event.preventDefault()
  const formData = getFormData(form.value)
  const data = formData.data

  // Check for spam bot honeypot field
  if (formData.honeypot) {
    return false
  }

  disableAllButtons(form.value)
  const url =
    'https://script.google.com/macros/s/AKfycbzuG3ea4BPkC27joSKGPmDTxtNqvP5cyXiNjeC_IRfpLhsyxmM7DMbxLvtUmfPxWmJw_A/exec'

  const xhr = new XMLHttpRequest()
  xhr.open('POST', url)
  xhr.setRequestHeader('content-Type', 'application/x-www-form-urlencoded')
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      form.value.reset()
      const formElements = form.value.querySelector('.form__elements')
      if (formElements) {
        formElements.style.display = 'none' //hide form
      }

      const thankYouMessage = form.value.querySelector('.thankyou_message')
      if (thankYouMessage) {
        thankYouMessage.style.display = 'block'
      }
      sending.value = false
      showSuccessModal.value = true // show success modal
      window.location.reload() // reload the page
    }
  }

  //url encode form data before sending as post data
  const encoded = Object.keys(data)
    .map(function (k) {
      return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
    })
    .join('&')
  xhr.send(encoded)
}

function getFormData(form) {
  const elements = form.elements
  const data = {}

  for (let i = 0; i < elements.length; i++) {
    let element = elements[i]
    let name = element.name
    let value = element.value

    if (name) {
      data[name] = value
    }
  }

  return { data: data }
}

function disableAllButtons(form) {
  const buttons = form.querySelectorAll('button')
  for (let i = 0; i < buttons.length; i++) {
    buttons[i].disabled = true
  }
}

Upon submitting the form, a confirmation modal appears and the page reloads to enable the form again for future submissions.

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

Identify when an ajax request is completed in order to trigger a subsequent ajax request

Within my project, I am faced with a challenge involving select option groups that dynamically load ajax data based on previous selections. The issue arises when I attempt to replicate this functionality for another select option group. Here is the scenar ...

Track the number of books read per month using an array of objects

Consider the following array of objects: const sampleArray = [{"read":true,"readDate":2021-01-15T18:21:34.059Z}, {"read":true,"readDate":2021-01-15T18:21:34.059Z}, {"rea ...

Error: Unable to locate Buffer2

I encountered the error Uncaught TypeError: Buffer2 is undefined when trying to import jsonwebtoken into my React project. The errors occur with both import jwt from jsonwebtoken and import {decode} from 'jsonwebtoken'. My versions are jsonwebt ...

Why is it that a click event outside of an HTML element cannot be detected in this Vue 3 application?

I've been diving into building a Single Page Application using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I'm focused on developing a search form within my project. Within the file src\components\TopBar.vue, here&apo ...

Images set as the og:image on the following 14 websites hosted on Vercel require authentication to be displayed

After deploying my Next.js 14 site on Vercel, I placed opengraph-image.png in the app folder alongside layout.tsx. Upon inspecting the meta tag, I noticed the following: <meta property="og:image" content="https://ns-website-6pnvd8ili-mare ...

How can I retrieve and store session information during the authorization event in Socket.io with express-sessions?

I have set up a websocket using Socket.io and the express 4 framework on a node.js server. Currently, I am working on implementing an authorization step for my users when they are using the websocket. Upon a user connection, a token is passed as a query ...

AJAX Code Causes Browser to Crash

Attempting to send user registration details using AJAX, here is an example of the code: <script> $("#submit_btn").click(function() { event.preventDefault(); var supplied_username = $('#desired_username').val(); var password = ...

Center both vertically and horizontally in Bootstrap UI Modal

I'm attempting to create a Bootstrap UI Modal that is centered both vertically and horizontally. While I found this solution that successfully centers the modal vertically, it loses its horizontal centering when applied to my own template with 800px ...

What is the best way to deactivate ng-repeat using a button in AngularJS?

How can I disable the apply button once it has been clicked by the user in a list of stores based on services? I am using ng-repeat to display the listing. Additionally, how can I write an apply function to disable a particular service once it has been app ...

Sending a unicode PHP variable to JavaScript is a breeze

I am attempting to transfer the titles and excerpts of Persian Wordpress posts to JavaScript. Below is the code in a .php script file: function change(){ document.getElementById("link").innerHTML = '<a href="$links[2]">$titles[2]< ...

Combining arrays based on a key in Node.js

I have the following two objects that need to be merged: [ { "response_code": 1, "response_message": [{ "a": 1000, "b": 1000001, "c": 10000002 }] }] [ { "response_code": 1, ...

Developing a side panel for navigation

My goal is to create a sidebar that shifts to the right from the left side and makes space on the page when the hamburger menu is pressed. I have made progress in achieving this, but I am encountering difficulties with the animation. const btnToggleSide ...

The functionality of the "Slots" prop has no impact when used on the material-ui Slider component

Trying to understand the purpose of the "slots" prop in relation to customizing how inner components like track and thumb are rendered within the Slider component. A basic example of rendering a Slider component is shown below const marks = [ { value: 0 ...

Generating permanent URLs for jquery and PHP

I am currently working on a website that utilizes jquery and php to dynamically post content. One thing I'm struggling with is figuring out how to generate permalinks for the site. I have an example link at www.eataustineat.com, but I want to create d ...

Transitioning to Vue 3: [Vue warning]: Prop already has a computed property named "actions"

Currently in the process of migrating a Vue 2 application to Vue 3, I've encountered an issue where I am frequently seeing this warning: [Vue warn]: Computed property "actions" is already defined in Props. This warning pops up in various c ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

Exploring the depths of jQuery promises

My journey into the world of promises has just begun, and I must say it's been quite intriguing. However, there are some questions that have been lingering in my mind. It seems to me that $.Deferred().promise, $.get().promise, and $.fn.promise().pro ...

Animation triggered by scrolling is not functioning/displaying div

I'm attempting to make a div fade up when it enters the viewport by using the library found at https://github.com/michalsnik/aos Unfortunately, all that seems to happen is that the div gets hidden. In the head section of my HTML file, I've refe ...

What's more efficient in terms of performance, checking for a class versus adding a class?

When dealing with a function that triggers on a scroll event, which method is more efficient? Checking if a class is already added and adding it if not Simply adding the class without any checks each time $(document).on('scroll', function ( ...

Retrieve the native interface from the Puppeteer browser/page context

Can a native interface be obtained from the Browser or Page instance to verify if an object is an instanceof this interface? For example, in a testing scenario with jest (where CanvasRenderingContext2D is not available due to being a Node context rather t ...