AngularJS does not clear the array after a POST request is made

ISSUE

Greetings! I am encountering an odd behavior with my backend. When I submit data, everything works flawlessly. However, if I press ENTER and submit an empty field, it reposts the previous value. Initially, I cannot submit an empty field, but after entering a value once, I can repeatedly post the same value by hitting ENTER on an empty field. The backend is built on Laravel 5.

MY CODE

HTML

<h1>{{ tasksdata.lists.name }}</h1>
<hr/>
    <div ng-repeat="task in tasksdata.tasks">
    <h2>{{ task.description }}</h2>
    </div>
<h2><a href="javascript:hideshow(document.getElementById('adiv'))"> + </a></h2>
<input type="text" ng-model="taskname" id="adiv" ng-keydown="key($event)" value="" onkeydown="hideshow(document.getElementById('adiv'))" class="form-control" style="font:24px bold; display: none" placeholder="NEW TASK" />

Script

function hideshow(which){

if (which.style.display=="none"){
    which.style.display="block";
    which.value="";
    which.focus();
}

$(which).keydown(function(e) {
    if (e.keyCode == 13) {
        which.style.display = "none"
    }
});

$(which).blur(function () {
    which.style.display = "none"
});
}

Angular for POST

myApp.controller('tasksController', ['$scope', '$log', '$http', '$routeParams',
    function($scope, $log, $http,$routeParams ){

        $http({
            method: 'GET',
            url: 'http://localhost/anydocopy/public/lists/' + $routeParams.id
        })
            .success(function (d) {
                console.log(d);
                $scope.tasksdata = d;
            });
            var task = {};
        console.log('before sending');
        console.log(task);
        $scope.key = function($event){
            console.log($event.keyCode);
            if ($event.keyCode == 13) {
                task = {
                    description: $scope.taskname,
                    list_id: $routeParams.id
                };

                $http({
                    method: 'POST',
                    url: 'http://localhost/anydocopy/public/lists/'+$routeParams.id,
                    data: task
                })
                    .success(function () {

                        console.log('true');
                        task = {};
                        console.log('after sending');
                        console.log(task);
                        $http({
                            method: 'GET',
                            url: 'http://localhost/anydocopy/public/lists/' + $routeParams.id
                        })
                            .success(function (d) {
                                console.log(d);
                                $scope.tasksdata = d;
                            });


                    })
                    .error(function(){
                        console.log('false');
                    })
            }};

    }]);

ATTEMPTS MADE

I have created a new task array before submitting, populated it with HTML data, and then performed the POST operation. If the POST was successful, the array is emptied. Strangely, the console displays an empty array before and after each POST request, yet the same data gets submitted when I hit ENTER. Furthermore, every time I display my input text, its value is always "".

Answer №1

To resolve this issue, consider implementing the following: $scope.taskname =""; after a successful post request. It seems that the two-way binding feature is causing the input field to revert back to its previous value, although it remains hidden due to display:none. Use your browser's developer tools to inspect the input field and you may notice that it still holds the original value.

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

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...

Organizing JSON objects into groups of x items

I am working with dynamically generated JSON data that needs to be grouped by a specific number. I have a method for generating the variable representing the grouping number, but now I need to organize the items based on that number. Here is the original J ...

insert data into modal's interface

I'm encountering an issue with my code, where the modal is not displaying the values inside the brackets as if they were not bound correctly. Everything else in the ng-repeat seems to be working fine, but for some reason the values are not being displ ...

Enforcement of Typescript Field Type Lax During Assignment

My current issue involves a constructor that is supposed to set the value of _device. The field is specifically designed to be of type number, and the constructor parameter is also expected to be of type number. However, when a parameter of type string is ...

Guide on deploying a Next.js React project with IIS on a Windows Server

Our goal is to deploy the application on an IIS server while ensuring it supports dynamic routing. After attempting to install IIS node, we are unsure of our next steps. Do we need to load a specific file like server.js in order to run the application ...

The fixed navigation bar shows a flickering effect while scrolling at a slow pace

Currently facing a challenge with our sticky navigation. Noticing a flickering issue on the second navigation (sticky nav) when users scroll down slowly. The problem seems to be specific to Chrome and Edge, as it doesn't occur on Firefox, IE11, and S ...

Wrap it in a ReactJS container tag

Today I encountered a frustrating issue while diving into ReactJS. I'm excited to learn by getting my hands dirty, but unfortunately, I keep running into this error: Adjacent JSX elements must be wrapped in an enclosing tag (47:14) And here's t ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...

What is the best way to create a new variable depending on the status of a button being disabled or enabled

Imagine a scenario where a button toggles between being disabled when the condition is false (opacity: 0.3) and enabled when the condition is true (opacity: 1). Let's set aside the actual condition for now -- what if I want to determine when the butt ...

Axios failing to transmit cookie information, despite setting withCredentials to true

Exploring the capabilities of React and Express to handle requests while including cookies. The communication between client-side and server-side is successful, however, the cookies are not being transmitted. On the client-side: import axios from 'axi ...

Launching URLs from JSON data in the system browser - Apache Cordova

I am facing an issue with opening links from a JSON in the system browser on both Android and iOS devices. The link generated by the function appears as: {{item.addressLink}}, instead of bit.ly/xyzxyz Here is what I currently have: <a href="#" ng-cl ...

Using Sequelize to Create/Post Data with Many-to-Many Relationship

I've been exploring how to implement a M:N Association using Sequelize. After examining the documentation (doc), I came across a solution that closely matches my requirements: User.belongsToMany(Profile, { through: User_Profile }); Profile.belongsToMa ...

Texture mapping in THREE.JS can be applied to ExtrudeGeometry for enhancing the appearance

Currently, I am tackling an issue concerning three.js and ExtrudeGeometry. The challenge at hand involves a wave-like structure composed of multiple individual frames, each being extruded using ExtrudeGeometry. https://i.sstatic.net/juEBb.jpg My goal is ...

Using node.js to parse an XML file from a URL and iterate through it to retrieve all the URLs contained within

I am currently utilizing the node module xml2js. The format of my xml file looks like this: <?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet type="text/xsl"?> <?xml-stylesheet type="text/css" media="screen" href="some url" ?> ...

What is the best way to access JSON data that is saved in a variable located within a separate component?

I'm currently utilizing axios to fetch JSON data from my API, mapping it, and storing it as a variable. I'm struggling to figure out the optimal way to call these variables within my React components. Retrieving and Storing JSON Data as Variable ...

Error: JSON parsing encountered an unexpected character "D" at position 1

When I call a python script as a child process from my node.js app to extract data from an uploaded file, I encounter the error 'UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token D in JSON at position 1" when uploading the file thro ...

Typeahead.js is a powerful tool offered by Twitter that allows for easy auto-completion

I am currently working on a program that has the capability to search for specific university courses based on certain parameters. Within my large JSON object, there are 1360 objects, each consisting of around 20-30 parameters. However, I am only intereste ...

Passing variables to each view in Node.js using Express

Currently working on coding a web-based game and looking to share variables across all views. Each user has their own unique race with various variables, such as commodities (money, energy, etc.) and planets (owned, built, etc). The goal is to display th ...

Trouble with variable in require path causing issues with r.js

As a newcomer to optimizing with r.js, I am also a big fan of requirejs build-config.js ({ appDir: "./src/main/webapp/webresources/javascript/", baseUrl: "./", dir: "./target/webresources/js", optimizeCss ...

Typescript: Verifying the type of an interface

In my code, I have a function called getUniqueId that can handle two different types of interfaces: ReadOnlyInfo and EditInfo. Depending on the type passed to this function, it will return a uniqueId from either interface: interface ReadOnlyInfo { item ...