Trouble with submitting a form and showing a success message in AngularJS version 1.6.8

My query submission form consists of fields for name, email, and the actual query. The component includes a controller function with a submit function to handle form submission.

To submit user input and display a success message upon submission, I utilize the ng-submit directive within the <form></form> tag.

Below are the respective files:

contact.html

<div ngController="contactController as vm">
        <div class="heading text-center">
        <h1>Contact Us</h1>
    </div>
    <div>
        <form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
            <div class="form-group row">
                <label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
                <div class="input-group">
                    <input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
                    <div class="invalid-tooltip">
                        Please enter your full name. 
                    </div>
                </div>
            </div>
            <div class="form-group row">
                <label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
                <div class="input-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="validationTooltipUsernamePrepend">@</span>
                    </div>
                    <input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email" 
                    aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
                    <div class="invalid-tooltip">
                        Please choose a valid email.
                    </div>
                </div>
            </div>

            <div class="form-group row">
              <label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
              <div class="input-group">
                    <input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
                    <div class="invalid-tooltip">
                        Please write your Query.
                    </div>
                </div>
            </div>
            <div class="btn-group offset-md-5">
                <button class="btn btn-primary" type="submit">Submit</button>
                <button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>  
            </div>
          </form>
          <span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
    </div>
</div>

contact.component.js

angular.module('myApp')
  .component('contactComponent', {
  restrict: 'E',
  $scope:{},    
  templateUrl:'contact/contact.html',
  controller: contactController,
  controllerAs: 'vm',
  factory:'userService',
  $rootscope:{}
});

function contactController($scope, $state,userService,$rootScope) {
  var vm = this;
  $scope.navigate = function(home){
    $state.go(home)
  };
  $scope.saveform = function(){

    $scope.name= vm.name;
    $scope.email= vm.email;
    $scope.query= vm.email;


    $scope.hideMessage = false;
    $scope.Message = "Your query has been successfully submitted."

  };
  $scope.user = userService;
};

//localStorage code

function userService($rootScope) {
  var service = {
    model: {
        name: '',
        email: '',
        query:''
    },
    SaveState: function () {
        sessionStorage.userService = angular.toJson(service.model);
    },
    RestoreState: function () {
        service.model = angular.fromJson(sessionStorage.userService);
    }
  }
  $rootScope.$on("savestate", service.SaveState);
  $rootScope.$on("restorestate", service.RestoreState);
  return service;

  $rootScope.$on("$routeChangeStart", function (event, next, current) {
    if (sessionStorage.restorestate == "true") {
        $rootScope.$broadcast('restorestate'); //let everything know we need to restore state
        sessionStorage.restorestate = false;
    }
  });
  window.onbeforeunload = function (event) {
    $rootScope.$broadcast('savestate');
  };
};

UPDATE: Upon submitting the form, when checking the response in the network tab of dev tools, only the markup is visible without the submitted values.

Answer №1

When setting up your template, make sure to use the method name saveform:

ng-submit="saveform()"

However, in your controller, the method is actually named save:

$scope.save = function() { ... }

To avoid confusion, rename it to saveform:

$scope.saveform = function() { ... }

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

Uninstall webpack-dev-server version 1.14.1 and replace it with version 1.14.0

Can someone help me with the process of uninstalling webpack-dev-server 1.14.1 and installing version 1.14.0 on Ubuntu using just commands? Error message: Uncaught TypeError: Cannot read property 'replace' of null at eval (eval at globalEval (jq ...

Changing the data type of a column in an Excel file from XLSX to

I am currently working with the XLSX npm package and attempting to download a sample Excel file, add some data to it, and then upload it back. The fields in the file include MOBILE NUMBER, DATE, TIME, and NAME. When I upload the file, the values for the DA ...

Enhance the appearance of CodeMirror substrings by applying bold formatting without altering

I am currently utilizing codemirror with primefaces extensions in XML Mode. I need to modify the font style of a specific substring to make it bold. For instance, <User> <Name>Micheal</Name> <Age>25</Age> <Addr ...

Exploring the Power of GraphQL Args in Mutation Operations

Currently, I am in the process of developing a blog service using express and apollo-express in conjunction with mongodb (mongoose). While implementing mutation queries, I have encountered difficulties in accessing the arguments of a mutation query. I am ...

The event SelectedIndexChanged is not triggering as expected on dropdown lists that are created dynamically

My Telerik RadComboBox triggers Javascript on change to fetch data from the database via AJAX and populate a second dropdown list. I need to fill text boxes based on the selection of the second dropdownlist. The code for the two dropdownlists is as follows ...

For an unknown reason, I am facing difficulties in using the Storage feature from @angular/fire in ANGULAR 16

Recently I started exploring Angular/Fire and decided to test out some of its features by creating a basic app. Firestore and authentication were working smoothly, but when I attempted to include Storage, an error message popped up: ERROR FirebaseError: ...

The file browser fails to open following an AJAX request in the Firefox browser

I am encountering an issue where the programmatic click on a file input does not open the file browser in Firefox after a successful AJAX call, although it works perfectly in Chrome. The problem persists on version 82.0.3 (64-bit) of Mozilla Firefox for Ub ...

Error: The requested collection# cannot be found in the Node.js Express routing system

Recently, I have started learning nodejs and implemented a simple API that allows users to log in with passport and then redirects them to the /collections route. While this part is functioning correctly, I am encountering issues with POST requests which a ...

An issue has occurred in AngularJS where the error message "ng areq not

I'm facing an issue with my meta controller, as I am trying to alter the meta tags dynamically. When checking the console, I encounter the error message error ng areq not a function. I have looked on StackOverflow for similar issues but couldn't ...

Angular is causing issues with removing slashes from strings within a Directive, potentially causing unintended alterations to the

Encountering an issue while learning Angular, where I am trying to replace any slash (/) in a string with equals (=). I have created a directive that wraps an element with a div and applies styling, particularly a background URL which is being replaced wi ...

Is there a way to ensure that an external file function completes before proceeding with the main code execution?

In my project, I have two key JavaScript files: main.js and load.js. Within load.js, there are two essential functions - getData, which makes an AJAX post call, and constHTML, which appends data based on the JSON array returned from the AJAX call. This app ...

Filtering a table based on user selection: specifying column, condition, and value using JavaScript

I am new to JavaScript and looking to implement real-time filtering on a table based on user input. My project utilizes Django and PostgreSQL for storing the table data. template <form action="" method="get" class="inline" ...

What's the process for changing this arrow function into a regular function?

Hello from a child component in Vue.js. I am facing an issue while trying to pass data from the parent via sensorData. The problem lies in the fact that the arrow function used for data below is causing the binding not to occur as expected. Can anyone gu ...

Difficulty Loading Static JavaScript File in Express.js

Currently in the process of setting up an express server with create-react-app. Encountering this error in the console: Uncaught SyntaxError: Unexpected token < bundle.js:1 Upon clicking the error, it directs me to the homepage htm ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

"Comparison: Java Installation vs. Enabling Java in Your Web Browser

Is there a method to determine if Java is currently running on your system or if it has been disabled in your browser? Our application relies on Java applets, and we typically use "deployJava.js" to load the applet. However, even when Java is disabled in t ...

What is the process for completing a form with Protractor and TextAngular?

I'm currently attempting to submit a form that utilizes TextAngular for certain input fields. Despite my efforts, I haven't been successful in finding information on how to fill out these fields. The closest solution I found was this, but when I ...

JavaScript Promise Chains- Issues with Functionality?

Could someone provide an explanation for why calling secondMethod in the Promise chain yields results, while calling secondMethod() does not? function firstFunction() { return new Promise(function(resolve, reject){ setTimeout(function() { ...

Utilize Vue-cli 3.x to load static resources

In my vue-cli 3 project, I have organized the static assets in the public directory. When compiled and built on localhost, all assets load successfully, except for some images not appearing in the browser. Despite guyana-live-logo.png, slide-1.jpg, and 97 ...

Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this: [{ "Consumer": [{ "Associated ID": "JSUDB2LXXX / BIC 7503 / US", "Parent Consumer": "7503" }], "Owner": [{ &qu ...