Angular JS is throwing an error because it cannot recognize the property 'push' of undefined

Would like to automatically update the div using $scope.push

encountering an issue:

Error: Cannot read property 'push' of undefined

Here are my JSON and JavaScript snippets:

JSON

{"records":[{"total":"156000"}]}

JavaScript

 $scope.plusCart = function() {
        $http({
            method  : 'POST',
            url     : 'http://localhost/so-ku/www/server/menu/plus_cart',
            headers : { 'Content-Type' : 'application/json' },
            data    : JSON.stringify({ rowid: $scope.currentItem.rowid, qty : $scope.currentItem.qty })
        }).success(function(data) {
            total_cart()
        });

    }
    function total_cart() {
    $http.get('http://localhost/so-ku/www/server/menu/total_cart').
        then(function(response){
            $scope.x = [];
            $scope.x = response.data.records;
            $scope.xtotal.push($scope.x.total);
    });
}

html

<div ng-controller="CartCtrl">
    <div ng-repeat="tot in xtotal" style="padding-top: 10px;">
        Rp {{tot.total}}
    </div>
</div>

Note : Seeking to have the div content automatically updated after submitting plusCart with $scope.push

Many thanks.

Answer №1

Based on the JSON data provided :

{"records":[{"total":"156000"}]}

The array response.data.records already contains the object [{"total":"156000"}]. Therefore, there is no necessity to reassign it within an array.

Corrected code :

  • Simply use $scope.x = response.data.records instead of creating a new empty array with $scope.x = []
  • Create a new array called $scope.xtotal.

Demonstration of Corrected Code :

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
  var jsonObj = {
"records":[{"total":"156000"}]
  };
              
  $scope.xtotal = [];              
  $scope.x = jsonObj.records;
  $scope.xtotal.push($scope.x[0].total);
  console.log($scope.xtotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="item in xtotal">
   {{item}}
  </div>
</div>

Answer №2

Since $scope.xtotal is not defined, an error is occurring when trying to push to the array.

See the adjusted code below:

function total_cart() {
    $http.get('http://localhost/so-ku/www/server/menu/total_cart').
        then(function(response){
            $scope.xtotal = [];   ///define the variable
            $scope.x = [];
            $scope.x = response.data.records;
            $scope.xtotal.push($scope.x.total);
    });
}

Answer №3

The array $scope.x contains the data {"records":[{"total":"156000"}]}

To assign all values from response.data.records to $scope.xtotal, you can use the following code:

$scope.xtotal = response.data.records;

If you prefer to do it manually and declare a variable as an array, follow these steps:

$scope.xtotal = [];
for (var i = 0; i < $scope.x.length; i++) {
    var obj = $scope.x[i];
    // make modifications to obj here
    // then push it to $scope.xtotal
    $scope.xtotal.push(obj);
}

Answer №4

Due to the fact that $scope.x (assigned as response.data.records) is already the suitable array

$scope.xtotal.push($scope.x.total);

it would be more appropriate to simply do

$scope.xtotal = $scope.x;

For further reference, view plunker: http://plnkr.co/edit/fo1kffVaIUKe3DrRDODN?p=preview

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

Is it possible to automatically submit a form at regular intervals without reloading the page and simultaneously insert the submitted data into

I am attempting to automatically submit a form every x number of seconds without refreshing the page and then insert the input data into a MYSQL database. The problem I'm facing is that while I can successfully insert the form's input value into ...

Navigating through the process of combining non-fixed key multilines of JSON into a single abstracted JSON structure

Given a large JSON file with 30 million entries like the following: {"id":3,"price":"231","type":"Y","location":"NY"} {"id":4,"price":"321","type" ...

Ways to transmit information from a modal to a function

Trying to figure out how to update data in an ng-grid after submitting a modal form with multiple text input controls. Should the ajax create function be called within the $scope.open controller section or resolve? $scope.open = function (size) { var mo ...

How to Utilize Output() and EventEmitter() for Value Transmission in Angular Application

Last week I was successfully able to implement Output() and EventEmitter() in my Angular app. However, today I am facing a new challenge while trying to apply the same concept in a different scenario. I'm not sure what I might be overlooking. Firstly ...

Could you provide some advice for creating a Single Page website?

I am working on a simple HTML setup with various elements such as a navbar and content blocks. <html> <head> <title>My HTML5 App</title> <meta charset="UTF-8"> <meta name="viewport" content="wid ...

Selecting multiple items from a grid using the Ionic framework

I am looking to create a grid of category images in Ionic framework, where users can select multiple categories and send their values to the controller. However, I'm unsure about how to make this happen with Ionic framework. Below is the view I curre ...

Tips for enlarging the box width using animation

How can I create an animation that increases the width of the right side of a box from 20px to 80px by 60px when hovered over? What would be the jQuery code for achieving this effect? ...

Utilize a solo input field to upload either a video or image, and showcase a preview of the uploaded content in a

I'm currently working on creating an input field that allows for the upload of both images and videos. Although I am able to successfully upload the files, I'm encountering an error when trying to display a preview. The code snippet below outline ...

PHP code saves empty value to JSON file

MODIFIED Issue - After executing the function, a null value is written to the JSON file. Expectation - Gather information inputted into an HTML form and add it to an existing JSON file. Here are some of the resources from Stack that I've referenced ...

The React-Chartjs chart is displaying without any color rendering

I attempted to create a radar chart using react-chartjs library, but I am facing an issue where the colors are not appearing when it renders. https://i.stack.imgur.com/tjAsW.png What could be causing this problem? I followed a significant portion of the ...

What went awry with my Angular form implementation?

I am new to using angular forms and I am attempting to validate an email field, displaying a message if the input is invalid. Although I thought I had done everything correctly, the error message is not appearing. <form name="Login" novalidate> ...

Is it possible to extract an attribute value from a parent element using ReactJS?

https://i.stack.imgur.com/OXBB7.png Whenever I select a particular button, my goal is to capture the {country} prop that is linked to it. I attempted the following approach import React, { useState, useEffect } from 'react' import axios from &ap ...

Insert a new element at the current scroll position without disrupting the existing scroll or view

My goal is to replicate the functionality of the Twitter Mac client. I have a scrollable box with a fixed height and multiple blocks inside. I want to add a new block before all the others, but keep it invisible to the user so they have to scroll to the to ...

Just ran $npm install and encountered an error message: "Module '../lib/utils/unsupported.js' not found."

Returning to work on a React project after switching from the Rails environment, I encountered an issue where I am unable to run NPM commands in my Mac terminal. Despite trying various solutions I found online, none seem to be effective. The real concern i ...

What is the best way to showcase a formatted JSON string on a webpage?

Currently, I'm in the process of creating a proof-of-concept React application that fetches data from the GitHub API. This app is designed to showcase the retrieved GitHub data as a JSON string within a paragraph element. Issue The problem arises whe ...

Is Jquery getting imported correctly, but AJAX is failing to work?

I am currently working on a Chrome extension that automatically logs in to the wifi network. I have implemented AJAX for the post request, but when I inspect the network activity of the popup, I do not see any POST requests being sent. Instead, it only sho ...

What causes differences in the resulting width between buttons and inputs as opposed to divs and anchor tags?

Check out this JS Bin: http://jsbin.com/ojiJEKa/1/edit I have a question regarding the different width results of <div> and <a> compared to <input> and <button>, even though they have the same style applied. Can anyone explain why ...

Clearing values using an AngularJS clear button

There is an issue with clearing a set of inputs in my code. It only clears when the input value is valid, but not when it's invalid. I have a workaround using an each loop to manually add something, but I'm hoping for a more concise solution. Pe ...

Template is not populating with data (Angular)

Currently, I am honing my Angular skills by working on a simple project. I have been seeking answers to my queries on Stack Overflow as they closely align with the issue I am facing. My challenge lies in displaying asynchronous data before it is initialize ...

Obtaining JSON data through AJAX requests from different domains may result in receiving a JSON string format

I have encountered an issue with my cross-domain AJAX call. It seems that instead of receiving a JSON object as expected, I am getting a string from the API provider. Here is the code snippet for my AJAX request. $.ajax({ async: false, ...