Is it possible to redirect a URL with a readyState of 4?

Is it possible to redirect to a page when the readyState is equal to 4?

    //load the send form
    if (sendRequest) {
        sendRequest.open("POST", urlRequest, true);
        sendRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        sendRequest.setRequestHeader("Connection", "close");
        sendRequest.onreadystatechange = displayStatus;
        sendRequest.send(sendData);
    } else {
        alert("fails"); //alert if request fails
    }
}

function displayStatus() {
    if (sendRequest.readyState == 4) {
        alert("send");
    // redirect to thank you page? 


    } else {
        alert("send fails"); 

} //end readyState

}

I am anticipating not getting a status code of 200.

Therefore, on readyState 4, I would like to automatically redirect to another page after the form has been sent. A simple PHP mail function using

<?php header(location: "url"); ?>
does not seem to be effective, so I believe utilizing Ajax or JavaScript is necessary...

At present, my current setup just isn't functioning as expected. Any suggestions for a solution?

Answer №1

Are you looking to trigger a redirect after the ajax request is successful? If so, you can achieve this by utilizing the jquery ajax() function and specifying the redirect code within the success callback.

For more information on the jquery ajax() function, you can visit http://api.jquery.com/jQuery.ajax/

Another simpler option is to use the post() method as an alternative. You can learn more about it at http://docs.jquery.com/Post

Answer №2

Is the code located within the sendRequest.onreadystatechange callback? It should be inside that callback, even if a 200 return is not expected.

Try this:

sendRequest.onreadystatechange=function(){
  //DEBUG
  alert("ready state change: "+ sendRequest.readyStat);
  if (sendRequest.readyState == 4) {
    alert("form sent");
    window.location = "http://www.mywebsite.com";
  }
}

Server-side will not work for two main reasons - first, the header has already been sent for the page making the request, and secondly, the requested page is AJAX so only the requested page will change, not the current one.

[EDIT] Have you checked the error console? Also, does this page involve frames by chance?

[EDIT 2]

I've created a jsbin where this works on Firefox and Chrome... http://jsbin.com/umufi4/2/edit

I believe the issue may not be with the location change if 'http://' is used in front of it, but rather how your sendRequest is constructed. Here are some errors I found, some of which may be related to jsbin and remote access, but if they exist on your end, they could be preventing it from reaching window.location

ERRORS: Refused to set unsafe header "Connection" XMLHttpRequest cannot load . Origin http://jsbin.com is not allowed by Access-Control-Allow-Origin. jromero.meFailed to load resource

Several questions arise:

  1. Is this a cross-domain request?
  2. Do you see the "send" alert box?
  3. Is sendRequest a global variable?

Answer №3

Appreciation to J.Romero for guiding me in identifying the problem and tweaking the script.

The issue was not related to cross-domain concerns, as the settings were properly configured. The alert box is functioning correctly, and the sendRequest function is global for all functions to utilize.

Only one error was identified, which was within the form itself. Instead of

onSubmit="return checkForm(this);" action=""
, it should be
onSubmit="checkForm(this); return false;" action=""
.

By returning a value of false with the onSubmit event, the form does not submit automatically. By appropriately configuring the JavaScript and AJAX, the form submission process can be finalized: validating the form, preparing it, making the AJAX call, verifying all inputs, sending the form, and redirecting to a thank you page.

Gratitude to everyone who offered their assistance!

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

Is there a way to change a mandatory field to optional in SuiteCRM?

I have two fields, field-A and field-B. The behavior of field-B depends on the value selected in field-A. If field-A has a value of 1, then field-B becomes a required field. To achieve this, I utilize SuiteCRM's addToValidate JavaScript function. How ...

Is it feasible to generate a fixed lighting effect overlay with HTML and CSS?

Is it possible to incorporate a static lighting effect overlay using HTML/CSS? My project consists of an HTML5/JS app with a top navigation bar and a series of cards that are transitioned through using swipe gestures. These cards are displayed in gray ove ...

Exploring Nodejs and delving into fundamental queries

As I delved into the world of Nodejs, I quickly realized that my knowledge was limited to just being a user. Transitioning to creating my own server posed challenges that were not easily resolved by online tutorials. This led me here seeking guidance to tr ...

What could be the reason for a Python server receiving a JSON message as None?

I'm a beginner in web programming and currently trying to grasp the concept of sending messages between a Python server and a JavaScript client. After stumbling upon a helpful guide at , I learned how to set up a Python server using Flask and send re ...

Ways to designate a parent element in Vue Draggable when the element is lacking a child

I'm currently incorporating vue-draggable into my project from the following GitHub repository: https://github.com/SortableJS/Vue.Draggable Below is my ElementsList component: <div> <draggable v-model="newElement" :move ...

"Provide information, then open a new webpage by clicking on a button. Perform various actions with the form by using type

Is there a way to quickly submit form entries to my database and then automatically redirect to a new page? My current situation requires that submitted information is stored in the DB before directing users to a thank you page, all in one seamless click! ...

Conceal the menu when tapping anywhere else

I am working on a project that involves implementing HTML menus that can be shown or hidden when the user interacts with them. Specifically, I want these menus to hide not only when the user clicks on the header again but also when they click outside of th ...

Creating a function in Angular to locate each object based on its ID

Hello there, I am currently working on creating a method called findChildByIdInData(data:any, childId:string). This method will take in a JSON main node with children that have unique IDs, and the goal is to find a specific object based on the ID provided ...

If the option of "none" is chosen, I would like to deactivate all checkbox selections

Struggling with disabling all checkboxes in a PHP form when the NONE option is selected. <h5>HEALTH OF STUDENT</h5> <p>Any physical, emotional, or other difficulties to be aware of?</p> <table> <td>Hearing ...

Disable menu bar | customize menu bar in electronJS

I am developing an Angular application with Electron.js. Due to the specific design requirements of my app, which is browser-based, I do not require or want the default Electron.js menu or menu bar to be displayed. Is there a way to remove it from my app ...

What is AngularJs's preference: URL or ID for templateUrl?

When looking at the AngularJS documentation, you will come across an example using the templateUrl property: In the HTML: //ngApp... <div ng-controller="Ctrl"> <div my-customer></div> </div> And in the controller: . ...

Chrome full screen mode can be toggled on websites after ajax data has loaded

I am currently experiencing a frustrating issue with Chrome on my webpage. The pagination feature loads content via an ajax call at: Whenever I click on the 2nd, 3rd, or subsequent tab in the pagination, the load process occurs but then suddenly jumps int ...

Exploring Methods for Retrieving offsetHeight and scrollHeight in AngularJS

I am currently developing a directive that requires three specific values: scrollTop offsetHeight scrollHeight projectModule.directive('scroller', function ($window) { return { restrict: 'A', link: function (scope, elem, attrs) { ...

Create reactivity in output by utilizing global functions in Vue

I've recently dived into Vue, along with vue-cli and Single File Components. I'm facing a challenge where I need to have a global function that provides formatted text to components throughout my application. This text should be based on the curr ...

When utilizing ajax in an MVC framework, an error was encountered due to the conversion of a datetime2 data type to a datetime data type resulting in an out-of

When trying to send data from ajax to the controller, I am encountering a title error. Oddly enough, when checking the datetime, it appears to be correct and displaying the current time accurately. Despite this, the same error persists. I have noticed tha ...

What could be causing the issue with the JS function that is preventing the button from

I am generating a button dynamically using my JavaScript function and then adding it to the DOM. Below is the code snippet: var button = '<button id="btnStrView" type="button" onclick=' + parent.ExecuteCommand(item.cmdIndex) + ' c ...

A guide to integrating ffmpeg with NuxtJS

I am completely new to Nuxt and currently in the process of migrating a Vue application that generates gifs using ffmpeg.wasm over to Nuxt.js. However, every time I try to access the page, the server crashes with the following error message: [fferr] reques ...

What is the best way to organize Node/Express routes based on their type into different files?

My /router/index.js file is becoming too cluttered, and I want to organize my routes by group (user routes, post routes, gear routes) into separate files within /router/routes/. Here's what I currently have set up: app.js var express = require(&apos ...

Configuring the array interval in an Angular application

I'm facing an issue while attempting to use the setInterval() function to update text for the user every 3 seconds. My attempt at looping with a for loop has not been successful - I only see 'test 03' and nothing else. I'm struggling ...

How can you display a personalized modal or error message using React context while incorporating dynamic content?

Can you please help me figure out how to display a custom modal or error message using react context with dynamic content? I attempted it like this: https://codesandbox.io/s/sleepy-wozniak-3be3j import React, { useState } from "react"; import ErrorConte ...