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

When using angularjs, the $window.location.href may cause the page to load without any

I have a dilemma where I have linked all my CSS and JS files in the index.html file, but subpages are located in a templates directory. When using $window.location.href, only a plain HTML page is returned without any CSS styles. The page renders fine when ...

Using parseFloat in JavaScript for German number formatting

Currently, I am working on incorporating a Vue.js component that is inspired by the example provided in this link: https://jsfiddle.net/mani04/bgzhw68m/. This is the structure of my source code: computed: { displayValue: { get ...

Having trouble adding state values to an object

I have a specific state set up in my class: this.state = { inputValue: "", todos: [] } My issue lies within an arrow function where I am attempting to use setState to transfer the value of inputValue into todos. this.setState({ inputValue: & ...

Easily refresh multiple select options by using the ajax updater function in prototype

After carefully reviewing the documentation for Ajax.Updater(), I noticed that the first argument to the constructor should be container (String | Element) – The DOM element whose contents will be updated as a result of the Ajax request. This can eith ...

What is the best method for transmitting all parameters via a URL?

$(document).ready(function () { $("#submitButton").click(function () { var name = $("#name").val(); var age = $("#age").val(); var gender = $('input:radio[name=gender]:checked').val(); v ...

How do the authentication and authorization processes in my frontend connect with the backend of my API system?

Currently, my frontend is built with Vue while my backend relies on an express rest API that fetches data from mysql. My goal is to ensure security for both the frontend (specifically a login form) and backend API without limiting access solely to my front ...

Using jQuery to access the value of the CSS property "margin-left"

I created a JavaScript game with moving divs that have different transition times. The game includes a function that is called every 1/100 seconds, which checks the position of the divs using: $("class1").css("margin-left") Here's the strange part: ...

Using the directive in AngularJS and passing ng-model as an argument

Currently, I am creating a custom directive using AngularJs, and my goal is to pass the ng-model as an argument. <div class="col-md-7"><time-picker></time-picker></div> The directive code looks like this: app.directive(' ...

Experience a dynamic D3 geometric zoom effect when there is no SVG element directly underneath the cursor

Currently, I am working on incorporating a geometric zoom feature into my project. You can see an example of what I'm trying to achieve in this demo. One issue I've encountered is that when the cursor hovers over a white area outside of the gree ...

Utilizing HTML5 to Access and Update custom data attributes

I have implemented the following code: var activeFilter = $('<li></li>').data('input-id', 'mycustomId'); $('#container').append(activeFilter); Now, I am faced with the challenge of retrieving a specific ...

Substitute dynamic Angular expressions with fixed values within a string

Inside my angular controller, I am defining a stringTemplate containing expressions like "{{data.a}} - {{data.b}}". Along with that, I have an object named data with values {a: "example1", b: "example2"}. My goal is to find a way to replace the dynamic ex ...

Retrieving external response data within a nested $http request

Excuse me as I am new to working with AngularJS. I am trying to figure out how to properly handle a nested $http call in my code, $http({ method: 'GET', url: host1, params: { 'format': 'json', } }).then(function ...

Retrieve data from the table and dropdown menu by clicking a button

A script is in place that retrieves data from two columns (Members, Description) dynamically from the table upon button click. Table html Here is the JQuery code responsible for extracting values from the table: $(function() { $('#myButton') ...

Creating an array of JSX elements or HTMLElements in a React TypeScript rendering

Currently in the process of developing a custom bootstrap card wrapper that allows for dynamic rendering of elements on the front and back of the card based on requirements. Here is the initial implementation: import React, { useState, ReactElement } from ...

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { return null; } retu ...

Is there an rxjs operator that includes both on-next and on-error callbacks?

Is there a similar function to promise.then(onNextCallback,onErrorCallback) in rxjs that I can use? I've already tried alternatives like pipe(concatMap(),catchError) but they are not what I am looking for. ...

Generate a fresh array using the information extracted from a JSON file

I need assistance in extracting a new array from JSON data. The desired output should be an array containing "itog" values. [12860498,20156554,19187309] [ { "0": { "itog": 12860498, "return": ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

What methods can be used to continuously send data to another web page within my website using XMLHttpRequest()?

As I delve into working with node.js and express.js, my primary goal is to efficiently tackle a specific issue. One of the pages on my website is tasked with receiving location data in latitude var lat and longitude var long. The challenge at hand is to c ...

A guide on converting JSON strings into arrays using Javascript

In my JavaScript program, I have a Mocha test that checks if all available currencies are displayed in a drop-down list: it('displays all available currencies in drop down list', () => { return invoiceEditPage.details.currencyDropDown.dr ...