When it comes to cookies and CORS, the browser won't save cookies if I submit a form without using preventDefault()

This is a snippet of JavaScript code that deals with setting up cookies and submitting a form.

import Helper from './helper'
import List from './itemList'
let myForm = document.getElementById('myForm');

function getAlfrescoTicket(e) {
    e.preventDefault(); //required for setting cookie
    let auth = {};
    auth.username = this.username.value;
    auth.password = this.password.value;
    let xhr = Helper.getXmlHttp();
    xhr.open("POST", List.ticketURL);
    xhr.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            Helper.setCookie('ticket', 
JSON.parse(this.responseText).data.ticket, 1);
            console.log(Helper.getCookie('ticket'));
        }
    };
    xhr.send(JSON.stringify(auth));
}

myForm.addEventListener('submit', getAlfrescoTicket);

The issue being faced here is when using e.preventDefault() to set cookies, the form does not submit and the page does not change. But if e.preventDefault() is removed, the form works fine and the page changes without setting up cookies. The challenge now is how to overcome this hurdle and have both cookies set up while also allowing the page to load properly.

Answer №1

To enhance your function, make sure to include myForm.submit().

By omitting e.preventDefault, the form will be submitted before your code completes its execution. By implementing e.preventDefault, your function will run without interfering with the default behavior of form submission (preventing the defaults!). Therefore, you will need to manually submit it yourself. One method is outlined in this explanation.

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

Submitting data from a dropdown menu using Ajax in Struts 2: A step-by-step guide

I have a select tag with the s:select element inside a form. My goal is to send a post request to the specified action using Struts 2 json plugin. I do not have much knowledge in javascript or jquery. <s:form action="selectFileType" method="post" ...

Revolving mechanism within React.js

I am currently developing a lottery application using React.js that features a spinning wheel in SVG format. Users can spin the wheel and it smoothly stops at a random position generated by my application. https://i.stack.imgur.com/I7oFb.png To use the w ...

Guidelines on managing the entry of users into a gaming room

While my question may not pertain directly to coding, I am feeling a bit lost and would appreciate insight into the thought process involved. Currently, I am working on developing a simple board game using Ajax and PHP. Although utilizing web sockets for ...

Retrieve the index of the selected element's child node

I need help determining how to identify the position of a specific child element within its parent. For instance, consider the following structure: <parent> <child>a</child> <child>b</child> <child>c</child> ...

Switch the image back to its original source after a brief amount of time

Looking for help with a function that changes the source of an image after a two-second delay, then reverts it back to a different random image: function ChangeToBomb() { var aantalPionnenOpScherm = $('#depionnen img') var randomPion = M ...

Optimizing performance: caching control for AJAX calls

One feature on my website involves using AJAX GET requests triggered by a button click. The URL structure for these requests typically looks like this: /php/getData.php?field1=val1&field2=val2 The data returned by getData.php using these values will ...

Activate or deactivate Reactstrap tooltip depending on the button's current state

I've chosen to use Reactstrap (version 6.5.0) for the styling of my ReactJs project. Within my inline form, I have a submit button that remains disabled until the user has input all mandatory details. The goal here is twofold: Show the user a tool ...

What is the best method for creating and passing a wrapped component to React Router?

I have multiple routes that I need to render different components for, and I want each component to be wrapped in a styled div. However, I'm looking for a way to write this code more efficiently. Is there a strategy to refactor this so that I can eas ...

Separately extract the input values from the divs

Here is a snippet of my HTML code: <div id="Section1" class="divFiles"> <input type="text" name="file"> <input type="text" name="file"> <input type="text" name="file"> <input type="text" name="file"> </div> < ...

Having a problem with the xmlhttprequest, not confident if it is being called correctly

I encountered a problem with the code I have where a user selects a sales center and it should trigger a currency change. Both selections are dropdowns, but when I choose a sales center, I receive an error saying ReferenceError: makeRequest is not define ...

Javascript use of overlaying dynamically generated Canvases

Currently, I am developing a game to enhance my skills in HTML5 and Javascript. In the beginning, I had static canvases in the HTML body but found it difficult to manage passing them around to different objects. It is much easier for me now to allow each ...

Ways to troubleshoot when a value does not get inserted into the database through ajax

I am facing an issue where my form data value is not being inserted into my database after submission. Prior to this, I successfully set the post data using ajax with ckEditor, but encountered errors from different inputs thereafter. The specific error mes ...

What are the steps to rename a file in Parcel without using automated tools?

Whenever I attempt to execute npm start or npm build, an error occurs stating that unknown: Entry /mnt/c/Users/kabre/Desktop/18-forkify/index.html does not exist. I was informed that Parcel could be renaming my index.html automatically. It's a bit con ...

Harvest information from a webpage

I am looking to extract property data from a particular website. While I have used mechanize successfully on other websites, I encountered some issues when trying to use it on this specific website. It seems that all the results are loaded via ajax calls. ...

Is it possible for one AngularJS application to influence another?

In my latest AngularJS project, I developed an application for user creation. Depending on the selected user type, specific input fields are displayed. Upon submission, the data is sent to the server in JSON format. So far, everything is working smoothly. ...

Element in Vue.js not recognized

Recently, I decided to dive into Vue.js as a beginner and started working on an app to manage my daily tasks. However, I encountered Vue Components along the way and ran into an error that has me puzzled: vue.js:1023 [Vue warn]: Unknown custom element: ...

What is the origin of the term "res" in a NodeJS http request handler function?

In many NodeJS applications, the following code pattern is commonly used: const express = require("express"); const app = express(); app.post("/some-route", (req, res) => { const data = req.body; } I am puzzled by the ...

Transferring large movie files (over 20MB) with the help of PHP and Ajax

I am currently facing an issue with uploading mp4 files using Ajax and PHP. Everything works fine when the file size is around 10MB, but I encountered a problem when trying to upload a larger file (I tested with a 34MB file). The uploader gets stuck and th ...

Warning on React component listing due to key issue originating from the parent component

Alert: It is essential that each child in a list has a distinct "key" prop. Please review the render method of ForwardRef(ListItem). A child from RecipientsList was passed. I have located this issue using the react-components debugger tool on Chrome. I ad ...

PHP - simplifying the process for AJAX requests

In the process of developing a PHP application that relies on AJAX for form submission via POST, I encounter situations where JavaScript may not be available. In such cases, I resort to traditional HTML/PHP form submission methods. My goal is to streamlin ...