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

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Preserve Text Selection While Utilizing DIV as a Button

I wonder if this issue is specific to the browser I'm using? Currently, I'm using Chrome... My goal is to enable users to save any text they've highlighted on the page with their cursor. I've set up the javascript/jQuery/ajax and it w ...

Tips for making a hide and reveal FAQ section

Currently working on creating a FAQ page for my website, I ran into a challenge. My goal is to have a setup where clicking on a question will reveal the answer while hiding any previously open answers. So far, I have managed to achieve this functionality p ...

Run an ajax function when a variable is populated with data

My current dilemma involves a session variable email=$_GET['email'];. I am seeking a way to trigger an ajax function only when this variable is available, and to set it to do nothing if the variable is not present. What is the technique for invo ...

Update the Vue method

Is there a way to optimize the following method or provide any suggestions on what can be improved? I am trying to create a function that converts author names from uppercase to only the first letter capitalized, while excluding certain words ('de&apo ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

I am facing issues with my submit buttons as they are not functioning

Once I hit the submit buttons, there seems to be an issue with redirecting to another page. Could anyone assist in identifying the error within this code and why my buttons "typ1" and "cod" are not redirecting to the specified location? <?php inc ...

Issue with the DocPad plugin for Gulp

I'm encountering an issue while trying to utilize the gulp docpad plugin. When I run docpad run, the following error message is displayed: Error: spawn UNKNOWN at exports._errnoException (util.js:837:11) at ChildProcess.spawn (internal/child_process. ...

Navigating through hidden input fields in Angular by utilizing the tab key

Seeking a method in Angular to navigate hidden inputs using tab functionality. I have several input forms that display only the text when not on focus. Is there a way to select an input and still be able to tab through the other hidden inputs? Any ideas o ...

How can I integrate date and time pickers in the view using CodeIgniter?

Trying to add date and time data into the database using a date and time picker. After dumping the results in the controller to ensure all fields are selected, I encountered an issue where only the time is being picked and the data is not being inserted. T ...

The playwright brings the curtain down on a blank page without a single word

I am working with code snippets const {chromium} = require('playwright'); (async () => { const userDataDir = '\NewData'; const browser = await chromium.launchPersistentContext(userDataDir,{headless:false}); const pag ...

Having trouble with getStaticProps serialization error in Next.js?

I encountered an error in my Next.js application that reads as follows: Error: Error serializing `.posts[0]` returned from `getStaticProps` in "/blog". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only ret ...

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

Executing a function within another function (triggering the logout action by clicking the logout link) in ReactJS

Is there a way to access a method outside the render function and call it inside another function in order to log out the user with a simple click? I encountered the following error: Cannot read property 'AuthLogout' of undefined Let me shar ...

Error: Angular does not recognize session storage reference

While my project is up and running, I have encountered an error in the terminal. let obj = { doc_id: sessionStorage.getItem('doc_id'), batch_no: sessionStorage.getItem('batch_no') } I attempted to make adjustments by a ...

Encountered an issue while trying to install using the command npm install react router dom

For a project I'm working on, every time I attempt to use this command, an error message appears and the installation fails. I've tried multiple commands with no success. Here is the specific error message: npm ERR! code 1 npm ERR! path C:\ ...

When using mapStateToProps in React Redux, it may encounter difficulties in reading nested values

I feel like I must be overlooking something very obvious, possibly related to Immutable.js/React/Redux. Here is a method I have... function mapStateToProps(state){ console.log(JSON.stringify(state.test)); //prints all nested properties and object ...

Trouble persists in saving local images from Multer array in both Express and React

I am having trouble saving files locally in my MERN app. No matter what I try, nothing seems to work. My goal is to upload an array of multiple images. Below is the code I have: collection.js const mongoose = require("mongoose"); let collectionSchema ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...