Retrieving JSON data from Python to JavaScript

One of my flask URL endpoints is /register, where I gather user input and handle it as follows:

@app.route("/register", methods=["POST"])
@login_required
def register_post():
    email = request.values.get("email")
    username = request.values.get("username")
    company_name = request.values.get("company_name")
    password = request.values.get("password")
    confirm_password = request.values.get("confirm_password")
    messages = register(email, username, password, confirm_password, company_name)
    success_message = (
        "Thank you for registering with us. We will get back to you shortly."
    )
    print("request values: ", request.values)
    print("messages: ", messages)
    if (len(messages) == 1) and (messages[0] == success_message):
        return jsonify({"code": 200, "message": messages[0]})
    else:
        return jsonify({"code": 400, "message": messages})

I want to show the messages in a browser pop-up based on the JSON data received. To access this data in JavaScript, I have the following AJAX call:

$.ajax({
    url: "/register",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
     success: function (json) {
        alert(json);
    },
    error: function (e) {
        alert(e);
    }
});

Although the JSON object is retrieved successfully, no alerts appear on the browser. What could be the issue?

Screenshots from the developer tools can be found below:

https://i.sstatic.net/KIk5O.png

Network tab https://i.sstatic.net/pe1L8.png

Answer №1

Your code is accessing the /register path, so the Ajax request being made by the JavaScript is not needed.

It seems like you are trying to send a form with an action="/register".

If you want to switch to using an Ajax request instead, follow these steps:

  • Add an event handler
  • Prevent the default form submission behavior
$('form').on('submit', evt => {
    evt.preventDefault();
    //... gather your data for the request body
    $.ajax(...);
});

Keep in mind that your current JavaScript code is missing the data property within the object passed to ajax. Make sure to include the necessary data for the request.

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

Retrieve impacted records using the mongoose update function

I am trying to find out how to retrieve the ids of affected records in a database when using the Mongoose update command with the multi:true option. MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, { multi: true }, function (err, raw) { ...

Tips for saving information from a textarea into an HTML file

I have a unique question regarding the usage of $fopen and $fwrite functions. My goal is to include a button named "save as HTML" below a textarea. Upon clicking this button, I want a popup box to appear mimicking the 'save as...' dialog window ...

Utilize AngularJS to refine and sort through data retrieved from an API

I have an Angular application that is fetching hotel data from an API. I want to filter the results based on the minimum price of the hotels being less than $50. $http.get($rootScope.baseurl + 'api/hotels/', { params: { page_ ...

The toggle in the dialog box refuses to submit the information

I am facing an issue with a dialog box that I am displaying using the jQuery .dialog() function. The dialog box contains a button that I want to use to post back to another page, but for some reason, it is not working as expected. I have tried setting the ...

What is the best way to make a fixed div appear when a user scrolls down the page, similar to Facebook

As I was scrolling down on Facebook, I noticed that the ads divs stay fixed when they reach the bottom. Has anyone figured out how to achieve this effect? I believe it can be done using a combination of JavaScript and CSS. Does anyone have the code for im ...

Is there a way to retrieve a file received in a response to a POST request using nodejs?

I'm encountering an issue with sending a POST command to download a file. I am attempting to send a POST request with a specific URL from the client side, along with a parameter that indicates the file to be downloaded. var req = $.ajax({ type: ...

Having trouble with the Keydown event - the image isn't moving as expected

Something seems off with my code. I have an image displayed on a canvas, but when I press the specified key, nothing happens. Can you help me figure out where I went wrong? let img = document.getElementById("ship"); let player = { x: 375, ...

Exploring the functionality of event.target.name.value

I've been struggling to make event.target.name.value work for an input field in my form. When I submit the form, the values appear as null and I have to click twice to get them. This is the code I've written: const [name, setName] = useState(& ...

Link components in Next.js now automatically add the current path when working with nested dynamic routes, making it

How can I effectively handle nested dynamic routes and utilize the Next.js Link component? Let's say I have 2 different file paths: /pages/projects/index.js <Link href={`/projects/${project.id}`} key={index}> <a>Project Name</a> ...

The e2e Protractor test is unable to identify the Angular component within a complex Angular router with multiple layers

I am currently working on an Angular application and I need to set up end-to-end testing for this project. Angular Package: 4.6.6 Protractor: 5.3.0 In addition, my project includes a multi-layer router that wraps the router-outlet into another component ...

My controller is not recognizing the DELETE $.ajax call - what could be causing this issue?

I've encountered an issue while attempting to delete an entity using AJAX. I have the following controller method: [HttpDelete] public ActionResult Delete(int id) { //Deletion logic return Content("OK"); } Within the view, my AJAX call looks ...

Is it feasible to have unique popups for individual textbox edits?

I am experiencing a problem with a popup in Asp.net while using AJAX modalpopup extender. I am wondering if it is feasible to display one type of popup when the user modifies certain textboxes, and another type of popup for the remaining textboxes. I beli ...

Issue with primeng dropdown not displaying the selected label

When using the editable dropdown with filter feature from PrimeFaces, I've noticed that selecting an option displays the value instead of the label. https://i.sstatic.net/8YFRa.png Here is the code snippet: <div class="col-md-5 col-xs-1 ...

What is the process for toggling a button using Vue.js?

Important Note: Implemented Vue.js and Vuetify.js for both functionality and styling. Utilizing the :class and @click properties, I managed to alter the background color of a button to a specified color. However, this modification is being applied to all ...

Manually detecting changes in the query string using AngularJS

My AngularJS application includes an edit form with a routing URL like app/edit/:id. When I navigate to app/edit/5, I am able to edit the object with ID 5. However, if I manually change the URL to app/edit/6, the application loads the object with ID 6 in ...

Updating JavaScript alert title in Android webview: A guide for developers

I have integrated a web view in my Android application, which contains a button. When the button is clicked, it triggers a JavaScript function that displays an alert box with the title "The page at 'file://' says". I would like to customize this ...

Is there a way to retrieve the JSON url from the input box

My goal is to retrieve a JSON file from a URL entered in a text box. I have identified the text box as txtr and used jQuery to get the value like this: var txtbval = $("#txtr").val();. I then included this value in the JSON parsing script as follows: url: ...

Refresh Quantity of item without needing to reload the page

I am currently working on a project and faced with a challenging situation. When a user adds a product to the cart, I need to verify both the quantity added and the specific product. To achieve this, I am utilizing a JQuery function. While the user is sti ...

How do webpack imports behave within a ReactJS project?

In my ReactJS project, I have utilized various 3rd party libraries such as lodash, d3, and more. Interestingly, I recently discovered that I did not explicitly write imports like import d3 from 'd3' or import _ from 'lodash' in all of ...

Error in Node.js React: Unable to add context property as the object is not extendible

Currently, I'm in the process of integrating an isomorphic react component into my node.js + express setup. However, as I attempt to add the component to my jade template for rendering, I encounter this error: TypeError: Can't add property contex ...