Troubleshooting: Why is Spring MVC failing to return results on ajax call?

I am trying to retrieve user data through an ajax request, but I am facing an issue where the success part of the request is not being reached and no logs are being generated.

This is the controller code:

@Controller
@RequestMapping(value = "/api/profile")
public class ProfilController {

@Autowired
public UserService userService;

@RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
public ResponseEntity<UserDTO> showData(@PathVariable String username) {
    User u = userService.findByUsername(username);
    if(!userService.findAll().contains(u))
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    return new ResponseEntity<>(new UserDTO(u), HttpStatus.OK);
  }
}

And here is my JavaScript file:

$(document).ready(function() {
console.log(localStorage.getItem('loggedIn'));
var usrnm = localStorage.getItem('loggedIn');

$.ajax({
  url: "http://localhost:8080/api/user/login/check/"+usrnm,
  type: "GET",
  headers: {"Authorization": localStorage.jwt},
  success: function(data) {
    console.log('success');
  }
})

$.ajax({
    url: "http://localhost:8080/api/profile/show/"+usrnm,
    type: "GET",
    success: function(data) {
        console.log('This part is not executed');
    }
  })
});

I am still learning Spring and programming in general, so please excuse any formatting issues in this question.

Answer №1

There could be a problem with the showData function. To address this, consider adding the following code snippet:

@PathVariable("username") String username

Answer №2

Let's try to eliminate this.

@Controller
@RequestMapping("/api/profile") // corrected and removed `value = `
public class ProfilController {
    @Autowired
    public UserService userService;

    @RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
    public ResponseEntity<UserDTO> displayUserData(@PathVariable String username) {
        User user = userService.findByUsername(username);
        if(!userService.findAll().contains(user))
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        return new ResponseEntity<>(new UserDTO(user), HttpStatus.OK);
      }
    }

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 is the process for including or excluding a class from a horizontal scrollbar?

I've been trying to implement a back to top button on a horizontally scrolling page. However, I'm encountering difficulties in adding or removing the necessary class to show or hide the button. Here's the JavaScript code I'm using: $( ...

ReactJS is giving me an error message: "Uncaught TypeError: Unable to access property 'ownerDocument' since it is null."

Trying to create a bar chart using D3 and render it with React's render method. Below is my index.js file: import React from 'react'; import ReactDOM from 'react-dom'; import './Styles/index.css'; import BarChart from &a ...

Firestore - Using arrayUnion() to Add Arrays

Is there a way to correctly pass an array to the firebase firestore arrayUnion() function? I encountered an issue while attempting to pass an array and received the following error message: Error Error: 3 INVALID_ARGUMENT: Cannot convert an array value ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Tips for creating text that adjusts to the size of a div element

I'm currently working on developing my e-commerce website. Each product is showcased in its own separate div, but I've encountered a challenge. The issue arises when the product description exceeds the limits of the div, causing it to overflow ou ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...

What is the best way to retrieve SQL results within the parent function's scope in NodeJS?

Currently, I am developing a Brackets text editor extension that stores work time in a database and allows users to view their time entries. The backend is built using Node.js to interact with an SQL server. So far, I have been successful in entering time ...

The conundrum of jsPDF's image compatibility

I am attempting to generate a PDF document on the client-side using the jsPDF library. The code I have written is as follows: <script type="text/javascript" src="libs/base64.js"></script> <script type="text/javascript" src="libs/sprintf.js" ...

Tricks for displaying a dynamic object tooltip in Three.js

Can anyone help me figure out how to create a HUD hint effect for a moving object? I envision something like this: An asteroid is floating through space, and when I click on it, a hint box with information pops up. I've been playing around with thi ...

Finding the inverse value from the Lodash get() function

My current approach involves utilizing the lodash get() method to retrieve values from an object. However, there are instances where I need to obtain negated values. Unfortunately, simply applying a negate symbol or negate method after retrieving the valu ...

Tips for including a line within a circular canvas

My progress bar crafted with css, javascript and html looks great (left image). However, I'm facing a challenge in adding white color dividers to enhance the appearance of the progress bar as shown in the image on the right. Despite my various attemp ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

The primary view seamlessly integrates with the page following the invocation of the partial view

Whenever the button is clicked, a different partial view is returned based on the selected value from the drop-down list. Controller: [HttpPost] public ActionResult Foo(SomeViewModel VM) { var model = VM; if (Request.IsAjaxRequest()) { ...

What is the best way to group/merge multiple objects that have the same name into a single object (Nesting)?

I have a dataset containing students' names and their marks in different subjects stored as an array of objects. My goal is to merge the data into a single object for each student with matching names, resulting in one record per student. Here is an ex ...

Adjust color scheme of drop-down menu

Having trouble changing the background color for my drop down menu. I tried to change the color for the sub div but it's not working. Can anyone help me fix this issue? Here is the code snippet: http://jsfiddle.net/3VBQ6/4/ #nav li:hover ul.sub li { ...

Concealing the pathway to a background image

Currently, I have a large grid made up of divs that display different sections of an image. By using background-image and background-position, I am able to showcase parts of the image. However, one issue is that users can easily view the complete image by ...

How to set the default value for an angularJS select dropdown

Can someone assist me with setting a default value for a select dropdown using AngularJS? I have explored similar threads on StackOverflow, but none of the suggested solutions have resolved my issue. Therefore, I am reaching out to seek help here. Essenti ...

Utilizing styled-components or personalized components alongside cypress

Cypress selector made simple: just use cy.get('.myComp') and it will select <input className="myComp" />. But when it comes to styled-components... Perhaps we have to resort to using custom attributes like cy-data or cy-testid. Sadly, it s ...

Exploring the seamless integration of Material UI with React version 18

I am having an issue with my background not turning black in React version 18.2.0 when using makeStyles from Material UI version 4. Despite no errors in the code, the background remains unchanged. How can I fix this problem? import './App.css'; i ...

Utilize Ajax to load an Ajax-driven page

Currently, I am in the process of developing a GreaseMonkey script for the ServiceNow CMS that includes jQuery/AJAX. The main purpose of this script is to retrieve the number of incidents using the filter option provided by ServiceNow for technicians throu ...