The function of adding data to a list in AngularJS seems to be malfunctioning

I have a JSON list that I am storing in an AngularJS variable called score

 $scope.jobTemplate = [{ type: "AddInstructions", visible: false, buttonText: "Add Instructions", editableInstructionsList: [{ Number: totalEditableInstruction, Text: "Instruction 1"}] },
    { type: "AddSingleQuestionsList", visible: false, buttonText: "Add Ques. (single Ans.)", singleQuestionsList: [{ Number: totalSingleQuestionList, Question: "What is your gender ?", Options: "Male1;Female2"}] },
    { type: "AddMultipleQuestionsList", visible: false, buttonText: "Add Ques. (Multiple Ans.)", multipleQuestionsList: [{ Number: totalMultipleQuestionList, Question: "What is your multiple gender ?", Options: "Malem1;Femalem2"}] },
    { type: "AddTextBoxQuestionsList", visible: false, buttonText: "Add Ques. (TextBox Ans.)", textBoxQuestionsList: [{ Number: totalTextBoxQuestionList, Question: "Who won 2014 FIFA World cup ?", Options: "text"}] },
    { type: "AddListBoxQuestionsList", visible: false, buttonText: "Add Ques. (ListBox Ans.)", listBoxQuestionsList: [{ Number: totalListBoxQuestionList, Question: "What is your multiple gender ?", Options: "Malem1;Femalem2"}] }
];

I am adding data on button click like this:

 // single questions..
$scope.InsertSingleQuestionRow = function () {
    totalSingleQuestionList = totalSingleQuestionList + 1;
    var singleQuestionsList = { Number: totalSingleQuestionList, Question: $('#SingleQuestionTextBoxQuestionData').val(), Options: $('#SingleQuestionTextBoxAnswerData').val() };
    $scope.jobTemplate[1].singleQuestionsList.push(singleQuestionsList);
    refreshSingleQuestionsList();
}

The newly added item appears correctly in the UI, but when I try to send the current scope variable data via HTTP post to the server, it does not contain the latest data.

$scope.ClientCreateTemplateFunction = function () {
    var clientCreateTemplateData =  $scope.jobTemplate;          
    var url = ServerContextPah + '/Client/CreateTemplate';        
    if (true) {
        //startBlockUI('wait..', 3);
        $http({
            url: url,
            method: "POST",
            data: clientCreateTemplateData,
            headers: { 'Content-Type': 'application/json' }
        }).success(function (data, status, headers, config) {
            //$scope.persons = data; // assign  $scope.persons here as promise is resolved here
            //stopBlockUI();

        }).error(function (data, status, headers, config) {

        });
    }
    else {
        $scope.showErrors = true;
        showToastMessage("Error", "Some Fields are Invalid !!!");
    }

}

I also tried using a global variable. I'm not sure why the scope variable works fine with the UI but does not work when sending the same data to the server via HTTP post. Please help.

I've included a snapshot where the UI shows two lists, while the console.log of the same scope variable only shows one list.

Answer №1

$scope.CreateClientTemplate = function() {
  var clientTemplateData = $scope.jobTemplate;
  var url = ServerContextPah + '/Client/CreateTemplate';
  if (true) {
    //startBlockUI('please wait..', 3);
    $http.post(url, $scope.jobTemplate).then(onSuccess, onError);

    function onSuccess(data, status, headers, config) {
      //$scope.clients = data; // assign  $scope.clients here as the promise is resolved here
      //stopBlockUI();
    };   

    function onError(data, status, headers, config) {};

  } else {
    $scope.showErrors = true;
    showToastMessage("Error", "Some Fields are Invalid !!!");
  }

}

Answer №2

To include a custom JavaScript object in a POST request, it is recommended to use jQuery's param method to convert the object into a string or encode it as JSON format.

 $.ajax({
            url: apiURL,
            method: "POST",
            data: $.param( customObject ),
            headers: { 'Content-Type': 'application/json' }
        }).done(function (data, status, xhr) {
            // Handle response data here
        }).fail(function (xhr, status, error) {
            // Handle error case
        });

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

Utilizing key values to access an array and generate a list of items in React.js

This marks my initiation on Stack Overflow, and I extend an apology in advance for any lack of clarity in my explanation due to unfamiliarity with the platform. My current task involves creating a resume with a dynamic worklist feature on my website. The ...

Vue - Utilizing child slots in the render method

Within my component, I am working with a default slot and attempting to enhance the layout by wrapping each item in the slot within a div. However, I am facing an issue where I need to retrieve the classes of one of the slot elements, but the VNode element ...

What is the significance of static in react?

export class NavMenu extends Component { static displayName = NavMenu.name; constructor (props) { super(props); this.toggleNavbar = this.toggleNavbar.bind(this); this.state = { collapsed: true }; } I attempted to research the ...

Tips for storing a JavaScript variable or logging it to a file

Currently working with node, I have a script that requests data from an API and formats it into JSON required for dynamo. Each day generates around 23000 records which I am trying to save on my hard drive. Could someone advise me on how to save the conte ...

Having trouble retrieving data from a JSON object that has been stringified. This issue is arising in my project that utilizes Quasar

I successfully converted an excel spreadsheet into a JSON object by using the xml2js parseString() method, followed by JSON.stringify to format the result. After reviewing the data in the console, it appears that I should be able to easily iterate through ...

Import .vue single file component into PHP application

I've been struggling to integrate a .vue single file component into my php app without using the inline template method. Since I don't have a node main.js file to import Vue and require the components, I'm not sure how to properly register m ...

Utilizing streams for file input and output operations in programming

This unique piece of code allows for real-time interaction with a file. By typing into the console, the text is saved to the file and simultaneously displayed from it. I verified this by manually checking the file myself after inputting text into the cons ...

Exploring the differences between Yeoman bower installation, npm installation, and grunt

This is my first time working on an AngularJS project and utilizing the Yeoman scaffolding tool (). I'm interested in incorporating fontawesome icons into my app () and I understand that I should use the following command: bower install fontawesome ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Using Restify to Serve CSS FilesLearn how to use Restify to

Currently, I am developing a node application that requires serving static files like JavaScript and CSS. In my project structure, I have the following layout: -MyProject -backend -index.js -frontEnd -index.html -js ...

React's JS is having trouble accepting cookies from the express server

I've encountered an issue where sending cookies from my express server using res.cookie() is not working with the front end. Even though I include {withCredentials:true} in the get requests, the cookies are not being set in the browser's applicat ...

When I clicked on the event in Javascript, the result was not what I expected

I am currently working on a web project centered around cooking recipes. In order for users to add ingredients to their recipes, they must input them one by one into a dynamic list that I am attempting to code using jQuery (AJAX). My issue arises when a u ...

The middleware code remains dormant and is left untouched

I am encountering an issue with this code that is supposed to create a folder if it doesn't already exist. When I debug and set a breakpoint on fs.mkdir, the code does not enter into it. Do you have any idea what could be causing this problem? ... ap ...

Angular: Leveraging real-time data updates to populate an Angular Material Table by subscribing to a dynamic data variable in a service

Seeking guidance on how to set up a subscription to a dynamic variable (searchData - representing search results) for use as a data source in an Angular Material Table. I have a table-datasource.ts file where I want to subscribe to the search results from ...

dynamic variable to store user input (Meteor)

I'm still trying to grasp the concept of reactive programming in Meteor, so I have a question that may seem silly: Instead of "injecting" data using the template system as documented, can I use it to extract data? For example, if I have a textarea li ...

CORS blocking Axios POST request to Heroku causing a Network Error 503

Using the MERN Stack, everything was functioning correctly until modifications were made to the UI (such as relocating code to different components and altering styles). The issue lies with a specific POST request, while other requests that utilize Axio ...

Erroneous Marker Placement Detected

Here is the data from my DataTable: Country Types of sales Total sales($) Name State United states of America chemicals 12662871 Obama GA Unite ...

Utilizing JavaScript to Invoke Controller Actions

Currently, my ASP.NET MVC actions return JSON data, which is then displayed on the screen by my client using jQuery's ajax function. The JavaScript code I use to call these controller actions includes absolute paths like this: $.ajax({ url: &apos ...

Generate JSON on-the-fly with ever-changing keys and values

I am new to coding and I'm attempting to generate JSON data from extracting information from HTML input fields. Can anyone guide me on how to create and access JSON data in the format shown below? { Brazilians**{ John**{ old: 18 } ...

What is the best way to input individual students' CA and exam scores into distinct fields and then calculate their total scores in a separate text field?

As a beginner in jQuery, I am looking for guidance on creating a script that calculates the Total score, Grade, Remark, and Position based on the user input of CAT score and EXAM score. The result should be displayed dynamically once both scores are entere ...