Redirecting with Flask using javascript upon successfully receiving json data

I'm currently using an ajax function to validate user login credentials and returning JSON data in case of errors. However, I'm facing an issue where I need to redirect to a specific URL upon successful login, but I can only send JSON responses from my function which rules out the possibility of using url_for or redirect methods. So, how can I dynamically retrieve the root URL in order to include it in the JSON response and then perform the redirection using JavaScript?

def logincheck():
    uname = request.form['username']
    pwd = request.form['password']
    if uname and pwd:
        this = userlogin.query.filter_by(username = uname).first()
        if this:
            if this.password == pwd:
                session['myid'] = this.uid
                return jsonify(success = ?)
            else:
                return jsonify(p_error = 'Incorrect Password')
        else:
            return jsonify(u_error = 'Incorrect Username')

Thank you.

Answer №1

Looking to retrieve the base URL in javascript?

var base_url = window.location.origin;

The output will be: ""

var host = window.location.host;

You'll get the output as: yoururl.com

If you need to redirect a URL using javascript,

// Redirects to another page

`window.location = "http://www.yoururl.com"`;

// This has similar behavior to an HTTP redirect

window.location.replace("http://yoururl.com");

// This simulates clicking on a link

window.location.href = "http://yoururl.com";

We hope this information proves helpful.

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

Bootstrap revamps dropdown menu code into a convoluted mess

I recently started working on a project with the Material Design theme from for a CodeIgniter application. However, I've encountered an issue with the dropdown functionality. It seems that Bootstrap is altering the original code, transforming it from ...

Tips for transferring information from ng-view to the navbar on the index.html page using AngularJS

Recently, I embarked on a journey to learn the MEAN stack and decided to challenge myself by building an authentication page from scratch instead of using the out-of-the-box solution. My main struggle lies in updating texts on my navbar. Here's a snip ...

Limit the number of rows per page when printing by utilizing JavaScript

In my PHP MySQL database, I have a table that displays all the data as shown in this https://i.sstatic.net/uM5tt.png image. I added a print button to put all the data into a hidden div and styled it as display none. When I click on the print button, the ...

Determining the Length of an Array in a JSON Message Object using Amazon Cloudwatch Logs Insights

Can the length of an array in a JSON object parsed by cloud watch log insights be obtained in any way? For instance, if a JSON object with the following structure is sent to log insights: { names: ['john', 'doe', 'joe', &a ...

Developing web components using angular.js while ensuring compatibility with IE11

I have an angular.js application where I need to initialize a web component. Everything runs smoothly on different browsers, however IE11 seems to have problems with document.importNode The angular.js onInit function is as follows: vm.$onIni ...

Tips for receiving a response from a jQuery.get request

I am encountering an issue on a page where I use the following code to send an AJAX request: function oc() { jQuery.get( "http://somewhere.com:5001/ajax/options/", jQuery('#selectform').serialize(), function(data,statusm,xml){ ...

Is it possible to customize the icon or color of the filter on a Kendo UI grid?

When I am filtering a kendo grid, I need to change the color of the "watering can" icon that appears above the columns. I have found a way to run my code on the filtering event: var originalFilter = self.object.data("kendoGrid").dataSource.filter; self.o ...

What are the steps for setting up Comet technology?

After spending a considerable amount of time developing web applications, I have recently come across the Comet server-side push technology. My understanding of this technology is still in its early stages. The link offers two simple example implementatio ...

Unable to implement recursive mapping within a React component

i encountered a problem that has got me stumped - I have an object named 'customerDraft' that contains nested objects. My goal is to render all the fields along with the fields inside 'customerDraft.metadata'. here is how my component ...

"Communication breakdown in Vue.js: $emit event not being picked up by corresponding $

Vue.component('rating-edit', { template:` <form> <input v-model="rating.title" type="text"> <textarea v-model="rating.remark">{{rating.remark}}</textarea> <button type="button" @click=" ...

Expanding list selection with jQuery_hover effect

I have devised the following code. HTML <ul class="treatment-menu"> <li>Menu always visible</li> <ul class="nav-child"> <li>Hidden sub menu</li> </ul> </ul> Hover function $(&a ...

Guide on making a PDF input field function like a regular input field with PDF.js

Whenever I encounter input fields in a pdf file, I attempt to use pdf js to interact with them. However, I have been facing challenges in doing so. Allow me to provide an example of my objective: const canvas = document.getElementById(`canvas-${this.page ...

Verify in Jquery whether a table row contains no elements with a specified class before removing any duplicates

I have an HTML table: <div class="1233">hello</div> <table cellpadding="0" cellspasing="0" class="sortable zebra tablesorter tablesorter-default" id="articles-table"> <thead> <tr class="tablesorter-headerRow"> ...

The form data is being passed as null to HttpContext.Current.Request

My file upload module is working well with Postman without any content type. However, in the code, the file count always shows as 0 in the backend API. If anyone has any insights into what I might be doing wrong, please help me out. Thank you. Below is my ...

How can I connect the Bootstrap-datepicker element with the ng-model in AngularJS?

Below is the html code for the date field : <div class='form-group'> <label>Check out</label> <input type='text' ng-model='checkOut' class='form-control' data-date-format="yyyy-mm-dd" plac ...

There was an issue stating that valLists is not defined when paginating table rows with AngularJS and AJAX

I found a helpful code snippet on this website for implementing pagination in AngularJS. I'm trying to adapt it to work with data from a MySQL DB table called 'user', but I keep running into an issue where the valLists variable is undefined, ...

Ways to find the image source using JavaScript/Jquery upon page loading?

I've scoured countless forums, yet a viable solution still eludes me. My objective is simple - upon page load, I want to gather all elements with the ".home" class and store them in an array called arr. Subsequently, the script should iterate through ...

I am trying to add JSON data to a file, but the output is not in a valid JSON format

I've been tasked with working on a file that prints out messages encoded in JSON format. { "Status": "Non_Malicious", "alert_level": "Low", "alert_count": 1, "alert": "", "hosts_alert": "" } Please note: e ...

Is Google Tag Manager causing a delay in the window.load event?

Upon loading my page, an ajax call is triggered. $(window).load(function() { updateDeliverySlots(); }); In addition, the Google Tag Manager javascript code resides at the top of the body section. Although it's recommended to place it in the head, ...

Traversing through a JSON structure to extract specific elements for future use

My API endpoint is returning a JSON response in the following format: [ { "id": 68663, "login": "test1", "url": "https://x.com/test" }, { "id": 67344, "login": "test2", "url": "https://x.com/test ...