When using AngularJS $http to send an object as a JSON key to a Spring controller, the returned value

I am attempting to transmit a json object from javascript to the Spring controller. My method of choice is using angularJs $http post for this. The issue arises when I send the key as object, with the lastName showing up as null. Strangely, if I send the string as a hard-coded value, it does get picked up in the controller. Below is the snippet of the controller code:

@RequestMapping(value="/edit", method= RequestMethod.POST)
@ResponseBody
    public void editInformation(@RequestBody UserDetails userDetails){
        LOGGER.debug("THE LASTNAME IS: "+userDetails.getLastName());
        //codes.....

    }

Now moving on to the angularJs part:

$fieldProperty =$(this).attr("name");
$inputValue =$(this).val();

$http.post("/app/edit", {$fieldProperty : $inputValue}).success(function(result){
                alert("Success "+result)
            }).error(function(data, status){
                //$log.info("The error is: "+data+ " and the error status code is: "+status)
                alert("failure"+" and the data is: "+data+ " and the stis "+status)
            });

When sending {$fieldProperty : $inputValue} as JSON, it results in userDetails.getLastName() returning null. However, sending {"lastName" : $inputValue} yields the desired outcome. I even checked by using alert($fieldProperty) which confirms lastName. Just a note that I am employing the Google Gson library.

If anyone can spot what I might be overlooking here, your assistance would be greatly appreciated. Thank you.

Answer №1

When working with $fieldProperty, it is important to define the object first. By declaring ({$fieldProperty : $inputValue}), you are adding the key '$fieldProperty' to the JSON object. This may result in receiving null for lastName in your Spring Controller. To avoid this issue, consider using the following approach:

$fieldProperty = $(this).attr("name");
$inputValue = $(this).val();
var params = {};
params[$fieldProperty] = $inputValue;
$http.post("/app/edit", params).success(function () {
      // Success Callback
});

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

In all tests, except for the initial one, the DOM is not updated by test-utils once triggers have been fired

I have been facing an issue with checking for error messages related to field completion in HTML/DOM after vuelidate is triggered. The functionality works properly after the click trigger, and all tests pass successfully - including mounting, element searc ...

Fixing the height of the body padding with JS or JQuery for a

I have a rather straightforward question that pertains to an issue I am facing while building a website using BS4. Specifically, my problem revolves around a fixed-top navbar with the class "fixed-top". The challenge stems from not knowing the actual heig ...

Tips on utilizing browser.getCurrentUrl() within a Protractor examination

I’ve been wrestling with these lines of Protractor code today: element(by.linkText("People")).click(); browser.waitForAngular(); var url = browser.getCurrentUrl(); ... It seems that getCurrentUrl always throws an error when placed after a waitF ...

The browser window's location is redirected to an empty page

I'm currently working on a website that has a similar layout to this (). https://i.sstatic.net/c7I2y.png My main issue is with the code I've written to detect a click on the linkedin div and redirect accordingly. <script src="https://ajax.g ...

Navigating through Dynamic URL Parameters with RouterLink in an Angular Application

Within my Angular 2 application, there exists a tab section where users can choose from a collection of separate yet contextually connected components. By clicking on one of these links, the corresponding component is loaded based on the routerLink definit ...

Gracefully Switching Between Various Functions

Suppose I have a collection of functions that perform various tasks: function doSomething() { console.log('doing something'); } function accomplishTasks() { console.log('accomplishing tasks'); } function executeAction() { console. ...

Is there a way to adjust this angular2 service to make it slightly more synchronous?

My goal is to create an Angular2 service that performs the following tasks: FTP to a remote server Read certain lines from a file Create a 'results' JSON object and return it to the component that called the service I have successfully impleme ...

Conceal a form depending on the referer_url parameter

I am looking to customize my 404 page by displaying a small form only when the visitor comes from a website, not from an email link or directly entering the URL. The purpose of this form is to address broken links that led the visitor to the error page. If ...

Strategies for Returning Multiple Values from a Function in JavaScript

Thanks in advance I am wondering how to extract multiple values from a code block using JavaScript. I am unsure if I need to use an array or something else as I am new to JS. Please consider the following HTML code: <div class="row"> ...

What is the best way to connect or link to a HTML table row <tr>

Is there a way to trigger an alert when the user double clicks on the whole row? ...

Guide on creating a project for developing an npm package

Within my git root project, I am utilizing a git subproject called UIComponents. For instance, my main project is named MyApp and the subproject is UIComponents. Currently, I have cloned the UIComponents repository inside my project folder and added UIComp ...

The process of encoding Point of Sale (POS) data as application/x-www-form-urlencoded

Can anyone provide guidance on how to correctly POST a URL encoded as application/x-www-form-urlencoded? I have all the necessary variables for the API suggestion below, but I'm struggling with posting it correctly. Thank you in advance for your help ...

Unable to install npm package from git source

I am attempting to install a package from a git repository that I had previously forked. Here is the command I tried: npm i catsaredoomed/invest-openapi-js-sdk --save-dev Unfortunately, I encountered this error message: npm ERR! prepareGitDep 2> npm W ...

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

Verify the occurrence of an element within an array inside of another array

Here is the scenario: const arr1 = [{id: 1},{id: 2}] const arr2 = [{id: 1},{id: 4},{id: 3}] I need to determine if elements in arr2 are present in arr1 or vice versa. This comparison needs to be done for each element in the array. The expected output sho ...

Searching with multiple key value pairs in jQuery autocomplete is not organizing the results

In one of my projects, I am using jQuery UI autocomplete search to look for subjects. However, I have encountered a problem. You can find a replica of the search implementation in this js fiddle. The first search uses a single JSON array object without an ...

Bringing a JavaScript function into a TypeScript file results in it being treated as a namespace

Trying to bring a vanilla JavaScript function into a TypeScript file within a React Native app has presented some challenges. The import process goes smoothly when working with JS, but switching to TS triggers the error message: Cannot use namespace &apos ...

What is the proper way to execute a JavaScript function within a JavaScript file from an HTML file?

I have the following content in an HTML file: <!DOCTYPE html> <!-- --> <html> <head> <script src="java_script.js"></script> <link rel="stylesheet" type="text/css" href="carousel.css"> & ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...

HTML5's drag-and-drop feature, including nested targets, allows for intuitive and interactive user

I'm currently implementing HTML5 drag and drop functionality. I have a parent div that is droppable, and inside it, there is another child div that is also droppable. <div id="target-parent"> <div id="target-child"></div> </d ...