After the request.send() function is called, the request is not properly submitted and the page automatically redirects

I'm currently working on a basic ajax comment form that includes a textarea and a yes/no radio button.

  • If the user selects 'yes', their comments are posted and then they are redirected to a new page.
  • If the user selects 'no', their comments are still posted, but they remain on the same page.

However, I've encountered an issue where when users select 'yes', the comments are not posted and the page redirects anyways.

Below is the current script:

// Grabbing the value of the yes/no radio button
flag_yesno = getRadioValue('form_comments', 'flag_yesno');

// Initiating POST request to process.php with timestamp appended
request.open('POST', 'process.php?t=' + new Date().getTime());
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

request.onreadystatechange = function()
{
    if(request.readyState == 4)
    {
        // Display response text in the comment_posts div
        comment_posts.innerHTML = request.responseText;
    }
}

// Setting up POST parameters
var params = "&foo=" + foo + "&bar=" + bar;

// Sending the POST request
request.send(params);

// Handling redirection after request.send() is triggered
if (flag_yesno=='yes')
{
    window.location = '/foo.php?foo='+foo;
}

Is there a way to properly manage the redirect without interfering with the request.send() function?

Answer №1

It is important to wait for the call to complete before taking further action. Trying to determine when it has been "fired off" can be challenging.

if(request.readyState == 4)
{
  if (flag_yesno == 'yes')
  {
    // If necessary, redirect to another page
    window.location = '/foo.php?foo='+foo;
  } 
  else
  {
    // Display the response text in the comment_posts div
    comment_posts.innerHTML     = request.responseText;
  } 
}

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

Currently using Mongoose and Luxon to showcase the event date, however, I am encountering an issue where the displayed date is one day earlier than expected

Currently, I am working with Mongoose and Luxon to present a date chosen by the user from a form. However, there seems to be an issue where the date is being console logged as one day, but appearing on the page as the previous day. Below is my model setup ...

issue with logging in, token verification failed

My current project involves creating a login system with authorization, but for some reason the token is not being transferred properly. const path = require('path'); const express = require('express'); const bodyParser = require(' ...

Using Jquery to send dynamic id and base url to a Laravel route

I have a jQuery script that uses AJAX to update the rating for a contest and sends the data to a controller to make changes in the database. My challenge is figuring out how to dynamically retrieve the contest ID and base URL of the website from the curre ...

Error: React unable to locate module './WebpackMissingModule'

Recently I started diving into React, and I'm encountering some difficulties trying to export components. Here is my current index.js file setup: import React from 'react'; import ReactDOM from 'react-dom'; import SearchBar from ...

"Steps to retrieve the button's ID when using the onClick event in Reactjs

Currently, I am working with Reactjs and Nextjs. I am utilizing functional components instead of classes. Within a loop, I have buttons and I am attempting to retrieve the id of the button when clicked using "onClick". Unfortunately, I am encountering th ...

Implementing Placeholder Text Across Multiple Lines with Material UI

Currently, for the React App I am developing, I am utilizing Material UI. In order to achieve a multi-line placeholder for a textarea using the TextField component, here is what I have so far: <TextField id="details" ful ...

Please tap to dial: Access to navigation is restricted

Trying to add a click-to-call link with the following code: <a href="tel:+4912345678912">Tel: +4912345678912</a> Despite Google developers saying it should work, major mobile browsers are blocking the navigation when clicking on the link. It ...

JavaScript: Creating keys for objects dynamically

const vehicles = [ { 'id': 'truck', 'defaultCategory': 'vehicle' } ] const result = [] Object.keys(vehicles).map((vehicle) => { result.push({ foo: vehicles[vehicle].defaultCategory }) }) c ...

How does the single-threaded nature of Node.js handle an abundance of concurrent requests?

I'm currently delving into the world of nodejs, trying to wrap my head around its single-threaded nature. Here's a pondering I have: Let's say I implement a non-blocking method and we have 20000 concurrent requests flowing in. If one request ...

Using jQuery setTimeout within a forEach loop

Currently, I am fetching an array of messages using 'getJSON method. My intention is to display each message for 3 seconds before moving on to the next one. The process involves loading an HTML file and applying a CSS class to each message. However, m ...

A guide to accurately accessing form data in Jquery Ajax requests

My beforeSend function is not working properly, as the background color does not change. I suspect it may be due to not correctly referencing the id variable posted from the form. Below is the relevant HTML and JS code: HTML <div id="rec<?php echo ...

Enhance the functionality of your React app by making the `<Paper>` component in Material UI clickable

I'm trying to figure out how to make a Paper component clickable. I attempted to set an id property in the tag like () and then utilize the DOM to add an event listener, but it's not working. I've hit a roadblock and I'm running out of ...

Exploring the concept of union types and typeguards in TypeScript

I'm struggling with this code snippet: function test(): any[] | string { return [1,2] } let obj: any[] = test(); When I try to run it in vscode, I get the following error message: [ts] Type 'string | any[]' is not assignable to type & ...

I am interested in creating a ranking system in JavaScript using JSON data based on points

I have a desire to create the following: var users = {jhon: {name: 'jhon', points: 30}, markus:{name: 'Markus', points: 20}}; // I want it to return like this 1. Jhon with number of points: 30 // 2. Markus with number of points: 20 ...

A "Uncaught TypeError" error occurs when trying to execute a function using the dollar sign

After successfully recognizing the hover function, the console displays an error message: Uncaught TypeError: $ is not a function <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(docume ...

Iterating through a JavaScript object

Just starting out with JavaScript and trying to figure out how to iterate through a JSON result that has been converted into a JavaScript object. const url = 'https://api.mybitx.com/api/1/tickers?pair=XBTMYR'; fetch(url) .then(res => re ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...

"Exploring the world of custom middleware in NextJs on a localhost

Question regarding nextjs page middleware: the documentation states that the request object should include geo, IP, ua, cookies, and nexturl properties. Visit the link for more information. I am attempting to retrieve the user's location using page m ...

Is there a way to forward to the "current" page in node.js without using middleware?

Users have the ability to log in from any page on the website. I am trying to implement a feature where the login form redirects to the current page the user is on and clears the POST data to avoid refresh problems. Despite my efforts, I have not been ab ...