Troubleshooting AngularJS POST Request Error with Request Body

I am a beginner in AngularJs and I am trying to make a post request to a server with enum form. Currently, I have the following JavaScript code:

function completeTaskAction2($scope, $http, Base64) {
$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode('kermit' + ':' + 'kermit');
$http.get("http://localhost:8080/activiti-rest/service/runtime/tasks")
    .then(function (response, data, status, headers, config) {
        var ids = response.data.data[0].id;

        $scope.formData2 = {
            taskId: ids,
            properties: [{
                    id: 'requestApproval',
                    value: ''
            }
            ]
        }
    });
$scope.submitForm2 = function () {

    $http({
        method: 'POST',
        url: "http://localhost:8080/activiti-rest/service/form/form-data",
        data: angular.toJson($scope.formData2),
        headers: {
            'Authorization': 'Basic ' + Base64.encode('kermit' + ':' + 'kermit'),
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    }).success(function (data) {

        console.log("OK", data);
    }).error(function (data) {

        console.log("Error Posting data...");
        console.log(data);
        console.log($scope.submitForm2);
    });
};

};

In the HTML file:

<div ng-controller="completeTaskAction2">
                        <div ng-repeat="x in names">
                            {{ x.name }}*

                            <form ng-submit="submitForm2()">
                                <a ng-if="x.type=='enum'">
                                    <select ng-model="formData2.properties[0].value" ng-options="y.name for y in x.enumValues " placeholder="{{ x.name[0] }}"> {{ x.name }} </select>
                                </a>
                                <br>

                                <button type="submit" class="btn btn-success btn-lg btn-block">
                                    <span class="glyphicon glyphicon-flash"></span> Submit Enum!
                                </button>
                        </div>


                    </div>
                    </form>

However, I am encountering this error:

Could not read JSON: Can not deserialize instance …

The response body is:

{"taskId":"67762","properties":[{"id":"requestApproval","value":{"id":"true","name":"Yes"}}]}

I only want to send this data to the server:

**{"taskId":"67762","properties":[{"id":"requestApproval","value":"true"}]}**

Can anyone help me fix this issue?

Answer №1

Make sure your ng-options are set up in the following format:

ng-options="y.id as y.name for y in x.enumValues"

By doing this, it will link the id of y to the model value rather than the entire y object.

Answer №2

Try this alternative approach:

<select ng-model="formData2.properties[0].value" ng-options="y.name for y in x.enumValues " placeholder="{{ x.name[0] }}"> {{ x.name }} </select>

You may want to consider using ng-selected in the following way:

<select ng-model="formData2.properties[0].value" ng-options="y.name for y in x.enumValues " ng-selected="x.name[0]"></select> 

This suggestion could potentially resolve the issue you are facing. Unfortunately, I am unable to test it at the moment. Please let me know if this solution works for you :)

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

Prevent selection on all elements except for input fields with the type of text

I am facing a challenge where I need to prevent selection on a website page for everything except input[type=text] elements. The answer provided in this accepted response to a similar query almost solves the issue. However, it doesn't stop users from ...

Exploring Bootstrap: Understanding column stacking and the requirement for a new row to stack upon resizing

I am currently mastering Angular and Bootstrap for a potential job opportunity, so I have decided to create a simple demo page. However, I am facing an issue with getting a new row to stack after the last div of the previous row when resizing. Initially, m ...

Ways to implement validation rules on Antd Form.List

I've created a form that includes a Form.List component for adding songs to an album. My goal is to enforce the requirement that every album must have at least one song, but unfortunately, Form.List only has the props name and children. Is there a w ...

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

Despite the div condition not being met, the code inside the div is still being executed

Even when the condition of the div is not met, it still runs the code within the div. <div ng-if = "1==11"> nishant <td><a href="indexForm.jsp?id={{x.id}}" class="btn btn-prima ...

Convert Binary Data to PDF Using Javascript Through Streaming

Upon requesting a Web-service, I received the following response (PDF file Streamed) %PDF-1.5 %µµµµ 1 0 obj <</Type/Catalog/Pages 2 0 R/Lang(en-GB) /StructTreeRoot 10 0 R/MarkInfo<</Marked true>>>> endobj 2 0 obj <</Type/ ...

What is the correct RegEx pattern I should use to properly match the provided test case without including the ending period?

Regular Expression: /@([\S]*?(?=\s)(?!\. ))/g Given String: 'this string has @var.thing.me two strings to be @var. replaced'.replace(/@([\S]*?(?=\s)(?!\. ))/g,function(){return '7';}) Expected Result: ...

Check for duplicate in AngularJS and replace with larger duplicate

I have this piece of code where I am currently checking for duplicates using the isDuplicate boolean. However, I now want to enhance my code by comparing another property called colorId and then setting the isBigger property for the larger one :) Do you ha ...

Having trouble changing the query string in the URL with Angular 4?

My search form includes various filters such as text inputs, checkboxes, and radio buttons. Whenever the user interacts with these filters, the query string in the URL needs to be updated. Consider the following scenario: http://example.com/search?myFilt ...

What is the best way to place a 3D model at random points on the surface of a sphere while ensuring that it always faces the right direction?

I'm faced with the challenge of placing huts randomly on a spherical world. While this task is feasible, the issue arises when the huts do not sit correctly - their bottom should be in contact with the tile below. I've experimented with the &apos ...

What is the proper way to document instance members that have been added through Object.defineProperties()?

I am struggling with JSDoc 3 recognizing instance properties defined using Object.defineProperties in my class. Here is a simplified version of the code I am working on: /** @exports mymodule */ function mymodule(exports) { /** @constructor * @p ...

Firebase Hosting integrated with Cloud Functions

Struggling with deploying my functions and hosting. While I have managed to get them working separately on different branches, integrating both hosting and cloud functions is proving to be a challenge. It seems like my cloud function is not deploying succ ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

JavaScript Bingo Game - Create Interactive Cell Selection

Below is the HTML code that I am using to create a Bingo card: ... <th class="orange">B</th> <th class="orange">I</th> <th class="orange">N</th> ...

Enable the expansion of a div by dragging and dropping an image onto it

Take a look at this fiddle. In this fiddle, I am able to drag and drop images onto the .drop-zone. However, I would like to enhance it so that when I drag an image onto it, the .drop-zone div expands to where I place the image. It's okay if the expand ...

React Query: obtaining the status of a query

In the realm of React Query, lies a valuable hook known as useIsFetching. This hook serves the purpose of indicating whether a particular query is presently fetching data. An example of its usage can be seen below: const queryCount = useIsFetching(['m ...

Exploring the concept of type identification in interpreted dynamic languages

How do dynamic scripting languages like Python, PHP, and JavaScript determine the datatype of a variable? /* C code */ int a = 1; int b = 2; int c = a * b; In the above C example, the compiler recognizes that 'a' and 'b' are integers. ...

Making a list of members from an array of objects

Let's say I have a collection of items structured like this: var itemList = [ { date: '22/9/2016', status: 1, id: '11111' }, { date: '23/9/2016', status: 1, id: '22222' }, { date: '24/9/2016&ap ...

What is the best way to emphasize a specific data point within a chart created with chartjs, especially when the data is sourced from a JSON

// Here I am retrieving another set of data in JSON format from a PHP file $(document).ready(function () { showGraph(); }); function showGraph() { $.post("phpfile.php", function (data) { console.log(data); var name = []; v ...

The shared module for next/router is not found in the shared scope default within Next.js and @module-federation/nextjs-mf

I am working on a JavaScript Turbo repo with a host app that has the following configuration in its next.config.js: const { NextFederationPlugin } = require("@module-federation/nextjs-mf"); const nextConfig = { reactStrictMode: true, ...