transfer to a different outlet when needing to circle back earlier

I'm currently working on implementing validation in a form, and one of the needed validations involves retrieving a value from an input field and checking its existence on the server or in a JSON file.

However, there seems to be a problem where even if the value exists and the proper return state is triggered, it still gets redirected. I suspect that the promise might have something to do with this unexpected behavior.

This is a snippet of my code:

$("#btnclick").click(function(){

    $.getJSON("locations.json", function(json) {

        var locations = _.filter(json, function(o) {
            return o.value == $originLocation;
        });

        if(locations.length <=0){
            console.log("The original location doesn't exist");

            //stop here
            return;
        }else{
            console.log("Yes, it does exist");

        }

    });


    window.location = "some link.php";

    // move to another link--> redirect

});

Answer №1

Upon reformatting your code, the error might become more evident:

$("#btnclick").click(function() {
    $.getJSON("locations.json", function(json) {
         var locations = _.filter(json, function(o) { 
             return o.value == $originLocation; 
         });

         if (locations.length <=0) {
             console.log("This origin location doesn't exist");
             //halt execution here
             return;
         } else {
            console.log("Yes, it exists");      
         }        
    });

    window.location = "some link.php";
    // proceed to another link-->redirect

});

window.location is always called on click. Utilize a promise chain structure. It appears you are aiming for the following logic:

$("#btnclick").click(function() {
    $.getJSON("locations.json", function(json) {
         var locations = _.filter(json, function(o) { 
             return o.value == $originLocation; 
         });

         if (locations.length <=0) {
             console.log("This origin location doesn't exist");
             //halt execution here
            return Promise.resolve(true);
         } else {
            console.log("Yes, it exists");      
            return Promise.resolve(true);
         }        
    }).then(exists) {
        if (exists) {
            window.location = "some link.php";
        }
    }
});

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

Flawed reasoning in determining the selection of checkboxes

Take a look at the code snippet below, featuring multiple checkboxes with corresponding fields: <Checkbox checked={checked[element]} onChange={(e) => { setChecked({ ...checked, [e.target.name]: !checked[e ...

Basic library using babel, TypeScript, and webpack - Error: (...) is not a recognized function; within Object.<anonymous>

Recently, I encountered a strange issue while trying to bundle a simple function using babel, typescript, and webpack. You can find the example that is not working at this link. To test it, simply download the code, run npm/yarn install, npm/yarn run buil ...

Having trouble with dynamic path generation for router-link in Vuejs when using a v-for loop?

//main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld.vue"; Vue.use(VueRouter); const router = new VueRouter({ routes: [{ path: "/", component: HelloWorld }] } ...

Utilize Angular2 with ES6 modules while running an Express server

Having some issues using ES6 Modules with Angular2 in an app served by Node.js and Express.js. When attempting to load the Angular2/ES6 app in browser, encountered this error message in the FireFox console: The stylesheet http://localhost:8080/boot.css w ...

Incorporating MongoDB into a Node/Express application file

Currently, I am delving into the realm of Mongo db with a specific goal in mind - inserting two variables into mongo. To achieve this, I have outlined the following steps within the same file: 1.- Defining the two variables 2.- Creating a function that ...

Steps for creating interconnected datepickers in jQuery with month and year selection:To create a dependent datepicker with month and year selection using

The JSFiddle I currently have is not functioning as expected. When the user directly selects the end-date, it does not restrict the start-date in this particular fiddle. It should change once the user directly changes the end-date. The functionality works ...

Smart method for repositioning multiple elements on the display

Imagine we have multiple divs displayed on a screen: https://i.stack.imgur.com/jCtOj.png ...and our goal is to move them collectively, either to the left: https://i.stack.imgur.com/KBfXC.png ...or to the right: https://i.stack.imgur.com/c1cUw.png An ...

Once the PostgreSQL container is stopped with docker-compose down, the previously used port becomes unavailable for use again

Currently, I am involved in a project which utilizes express as the server and postgres as the database to delve into dockerization. The server relies on the database being operational. Initially, when running docker-compose up everything functions correct ...

Change the name of "rows" in the findAndCountAll method of Sequelize

Is there a way to change the key name for result.row when utilizing findAndCountAll in Sequelize? For pagination purposes, I am implementing findAndCountAll. The data structure I receive is as follows: { "count": 8, "rows": [ { ...

Modify the transition and design of two progress bars

I'm having an issue with merging two Bootstrap progress bars into one. Initially, the first progress bar appears when the page loads and hides after data is loaded. At the same time, the second progress bar shows up. However, the transition animation ...

Browser displaying a CSS error: "Invalid property name" while applying pseudo-element :after

I encountered an issue in Chrome and Explorer while attempting to set a CSS property for a pseudo element :after. (I'm trying to create a styled burger nav icon) The error message I received was: 'Unknown property name' This happened wh ...

Adding a uniform header and footer across all pages simultaneously in HTML

I am currently working on a project where I want to apply the same header and footer design from my homepage to all pages. However, I need a method that allows me to update the header and footer in one place, so that any changes I make will automatically r ...

Is there a way to sort data by year and month in mongodb?

I'm trying to filter data by year in MongoDB based on a specific year and month. For example, if I pass in the year 2022, I only want to see data from that year. However, when I try using the $gte and $lte tags, it returns empty results. Can someone g ...

Using Selenium Webdrivers to Browse Pages with Minimal Resource Loading

I'm attempting to restrict Javascript from altering the source code of the site while testing with Selenium. Disabling Javascript completely in the Webdriver is not an option as I require it for testing purposes. Below is my approach for the Firefox W ...

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

Updating an Object in vue.js Upon Click Event to Add a New Value

I currently have a code snippet that looks like the following: arr = [ { val1: a, val2: b }, { val1: a, val2: b }, { val1: a, val2: b } ] <div v-for="single in arr"> <button v-on:click="addSome"></button> </div> When I c ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

The Alphavantage was acting strangely when I ran a Google script

After following a tutorial video on YouTube, I was confident that my Google script for Google Sheets was working perfectly. However, I encountered two strange issues that I just can't seem to figure out. The code below is exactly what I need - it ...

Google Maps autocomplete feature is causing the input to update only after clicking in ng-model

After fetching a Google Maps place ID from a REST API, I utilize the Google Maps API to retrieve the place object in this manner: var geocoder = new google.maps.Geocoder; geocoder.geocode({ 'placeId': data.city }, fun ...

JavaScript for creating dropdown menus using Twitter Bootstrap

I've been struggling to get the dropdown menus in my Twitter Bootstrap project to function properly. Below is the code I have for the navbar: <div class="container-fluid"> <div class="row-fluid"> <div class="span12"> < ...