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

Strange padding issue found on View component in React Native Web when using Edge browser

While developing a Button in react native for the web, I noticed an unusual padding issue when viewing the button in Edge. Despite my efforts to debug, I have not been able to find a solution. Strangely, the button appears correctly on Android and Firefox. ...

Getting the parameters of a path from the URL's breadcrumb in Vue.js

Currently utilizing Vue Attempting to include path parameters in breadcrumb URLs for my app's router. Looking to achieve something similar to the following: { path: 'pages/gestion/region/:reg', name: 'gestion-depa', ...

Prevent selection based on JSON information

I am utilizing the Jiren filter library to sort through JSON data. If a particular filter criteria does not match any of the results, I would like to disable that option in the select dropdown. For instance, if "Silversea Expedition" is not found in my re ...

Dividing Faces with Lengthy Edges in three.js into Two Separate Faces

I am currently working on a script that involves splitting overly long edges of faces into two separate faces instead of one large face. The final result is exported to a .obj file. Although the geometry reduction works fine, I have noticed some issues a ...

ng-click="showInventory()" onClick="currentTemplate='/inventory.html'" Not

I'm facing an issue with my menu list. When I apply the ng-repeat directive, it seems to not work properly. However, when I remove the ng-repeat, everything functions as expected. <div class="reports_header_tabs_holder"> <span ng-repea ...

Tips for creating a responsive iframe without relying on aspect ratio assumptions

Is there a way to create a responsive iframe without relying on a fixed aspect ratio? The width and height of the content are unknown until rendering. Keep in mind, using Javascript is an option. For instance: <div id="iframe-container"> <i ...

Effortlessly deleting a row with JQuery and PHP without reloading the page

I am currently working on creating a jQuery function to delete a div, but I'm facing an issue. Whenever I click the submit button, the div is not being removed and the page gets refreshed. How can I achieve this without refreshing the page? You can ...

Modify the date parameter in a Python URL request

My goal is to retrieve varying data from an API by adjusting the date in each request. I am considering using a for loop or counter to iterate on the days and months, pass this information to the variables below, and then concatenate the complete URL. Here ...

Refreshing the current window with the ``Window.location.reload()`` function

I have integrated a map that displays clients using markers. The map I am utilizing is Leaflet with an AngularJS directive. The issue I am facing is that when I initially access the map, it functions correctly. However, when I change routes, all the marke ...

What is the best way to import API Endpoints from various directories in an Express Server?

I have been using a script to load my API endpoints like this: readdirSync('./routes/api').map((r) => app.use( `/api/v1/${r.split('.')[0]}`, require(`./routes/api/${r.split('.')[0]}`) ) ); This script reads eve ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

Refresh database post drag and drop operation

I am seeking a way to update a "state" SQL row after dragging an element between the "DZ", "WT", and "ZK" divs. Below is a snippet of my code: SQL queries: $sql = "select * from tasks where login = '$user_check' AND state = 1"; $sqlDodane = mys ...

Can a websocket be used to communicate with a server that is not the same as the one hosting the html5 website?

My goal is to establish communication between a hardware device and an HTML5 website. It seems like the best way to do this would be through WebSockets or possibly WebRTC over a WiFi network. Is that correct? I haven't come across any solutions invol ...

Retrieving Outdated Information through the Express Framework

Whenever I make a fetch request to a node express server, it sometimes returns old data that was previously fetched from the same endpoint. This issue occurs sporadically but seems to happen more often than not. Even after disabling Cache-Control in the f ...

What is the best way to extract data from a JSON response?

Looking to parse a JSON response with a JSON array nested inside another JSON array. Any tips on how to efficiently parse it? Hoping for the best example of multiple JSON array parsing. All fields are dynamic so need this kind of response from developers ...

When individuals discuss constructing a stack, or a full stack, in JavaScript, what exactly are they referring to and how does this concept connect with Node JS?

I recently started learning about node.js, but I'm struggling to understand its purpose. I have experience with JavaScript/jQuery and Angular, so I don't see how Node can benefit me. People keep talking about full stack JavaScript but I'm st ...

Having trouble with opening and closing popup windows in JavaScript while using Android frames?

To display additional information for the user, I create a new tab using the following code: window.open("/Home/Agreement", "_blank"); Within the Agreement View, there is a button with JavaScript that allows the user to close the Popup and return to the m ...

What steps should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

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 jqGrid to load additional JSON data after the initial local data has already been populated in the

I encountered a specific issue: I have a compact form with four choices. Users can choose to fill them out or not, and upon clicking 'Ok', a jqGrid is loaded with data based on those selections. To accommodate dynamic column formatting, my servle ...