Troubleshooting script error: Dealing with Ineffective Redirects

I am currently using a JavaScript code that allows users to jump to a directory by typing its name. Here is how it functions: If the input field is left empty, the user will be directed to a page called "error.html" which displays the message "This field cannot be empty." In case the directory name does not exist, the user will be redirected to "error2.html" with the message "Looks like this page doesn't exist." However, I have encountered an issue. There is a directory named 333, and when I enter the name of this existing directory (333), instead of being redirected to the correct location, I end up on the "error2.html" page. I would greatly appreciate any assistance in fixing the script above.

<form action="javascript:void(0)" name="f1" onsubmit="jump();">
    <input type="text" name="k1" value="" placeholder="Enter the name of the directory"/>
    <input id="submit" type="submit" name="s1" value="check">
</form>
 
<script>
    function jump() {
        var directory = document.f1.k1.value.trim();
        if (directory === "") {
            window.location.href = 'error.html';
            document.f1.k1.focus();
            return;
        }
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4) {
                if (this.status == 200) {
                    window.location.href = directory;
                } else {
                    window.location.href = 'error2.html';
                }
            }
        };
        xhttp.open("HEAD", directory, true);
        xhttp.send();
    }
</script>

Answer №1

After firing the onsubmit="jump();" event, you proceed to submit the form without pausing for the ajax response. It might be more beneficial to interrupt the event.

One solution could be to include

onsubmit="jump(); return false"
, although some individuals prefer utilizing ev.preventDefault() where ev refers to the event passed as an argument to the listener, jump(ev).

Hint: utilize the devtools with "Persist" activated so that error messages remain visible even after reloading a new page.

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

What could be causing my controller method in TypeScript to throw an error message unexpectedly?

Hey there. I'm diving into TypeScript and currently working on converting an Express backend to TS. Everything was smooth sailing until I encountered some unexpected issues. Specifically, the lines const hasVoted = poll.votedBy.some((voter): boolean = ...

Ajax: everyone utilizing a rapid application development (RAD) tool

Looking for recommendations on a RAD tool for AJAX interface programming. Has Grails been effective for this task? ...

Failure to successfully transmit data from Ajax to PHP script

When I click on a button in my HTML page, I am trying to retrieve information from my PHP code, but it is not connecting properly. The front page displayed in index.php is as follows: <!DOCTYPE html> <html> <head> <link rel="styleshe ...

Removing using modal with AJAX in Laravel version 10

Upon clicking to retrieve data('product-id') from the delete-btn for the first time, I was able to get $product->id and successfully delete it. However, when I attempted to delete another product, it failed. It seems like it didn't retri ...

The 'otherwise' controller in AngularJS does not execute when the resolution in another controller has not been successful

Imagine having routes set up in the configuration: $routeProvider .when('/person/:person_id', { controller: 'person', templateUrl: 'partials/person.html', resolve: { data: ['api', '$route', ...

How can we prevent excessive hook calls when utilizing components in React?

I've run into an issue with the modal component hook I created below. I want to set up this modal at the app level so that I can easily access it via a global state like Zustand whenever necessary. Here is the structure of the modal component: Crea ...

Is there a way to assign a unique scrollTop value for a specific scrollspy location?

I have a custom script that tracks the current position within a menu and applies an active class to it. However, I require specific rules for the ID contact_form. Specifically, I need to add 1000px to the scrollTop value for that particular ID location. ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

Determining the specific condition that failed in a series of condition checks within a TypeScript script

I am currently trying to determine which specific condition has failed in a set of multiple conditions. If one does fail, I want to identify it. What would be the best solution for achieving this? Here is the code snippet that I am using: const multiCondi ...

Steps to Change the Default Value of Ant Design Date Picker upon Date or State Modification

AntD Version : 5.0 Upon loading the page, the default date is displayed, but I am passing a date stored in a state object. However, after successfully loading the page, changing the state of the date from one component does not update the default value of ...

Unable to access the posted variable through AJAX requests

I need help with sending a variable "id" to another PHP page using Ajax. It seems that the variable is not set in the second PHP page called "export.php, where I want to use it to query a MySQL table and display the results in an HTML table. Can you assis ...

Next/image is encountering an error due to an invalid Element type being generated

Trying to utilize the next/image feature to display an SVG image is causing me some trouble. Every time I attempt this, an error message pops up: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

Which data structure is suitable for storing a JSON object?

Currently, I have a form set up in the following way: using (Ajax.BeginRouteForm( ... new AjaxOptions { HttpMethod = "POST", OnFailure = "OnFailure", OnSuccess ...

A step-by-step guide on smoothly transitioning between elements using Vue-Carousel on a click event

Today marks my first question here and I'm excited! Can anyone guide me on how to implement sliding on click element with Vue-Carousel? I want to slide to the right with just a single click on my input button. Here's the code snippet I have base ...

AJAX call using jQuery not returning the expected callback result

My goal is rather straightforward: I want to store the object retrieved from Instagram's API in a variable so that I can manipulate it as needed. Here is my current progress: $(document).ready(function() { // declare variable var instagram_infos; fu ...

Executing a Knex RAW MySQL query to insert new records into a database table

As someone new to working with MySQL, I have previously used PSQL in a similar manner. However, the following code is generating an error. return await db .raw( `INSERT INTO users(firstName, lastName, email, ...

Switch out the name of multiple elements with mootools

Is there a Moo tool that can replace multiple element IDs? I currently have the following code: $$('myelement').each(function(el){ var get_all_labels = el.getElements('label'); var get_label_id = get_all_l ...

Using jQuery to dynamically add or remove table rows based on user inputs

Apologies if this is too elementary. I am attempting to insert rows into a table if the current number of rows is less than what the user requires. Simultaneously, I need to remove any excess rows if the current number exceeds the user's specificati ...

Issues with the functionality of the accordion menu

I have implemented an accordion menu on my website. However, I am facing an issue where the 2nd menu always slides up when it gets loaded instead of sliding up after clicking on it. I want the behavior to change so that the sub menus elaborate only upon cl ...

Is there a way to undo the click event in Javascript?

Is there a way to revert back to the initial position after clicking? I successfully changed the x icon to a + icon on click, but now I'm struggling to reverse that action. I've tried using MOUSEUP and DBLCLICK events, but they aren't ideal ...