Error Checking in AngularJS Form Submission

According to my form.json file, I have a form that needs validation and a simulated submission.

  • Firstly, I need to address this issue: fnPtr is not a function
  • Next, I want to submit the form to a mocked API endpoint that will return true or false. Can I utilize https://docs.angularjs.org/api/ng/service/$http for this purpose? If so, how can I achieve it?

When submitting the form, I need to send an AJAX request which will gather the form data, send it to the specified endpoint, and receive some data in return.

View the demo on Plunker

JS

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

myApp.controller('mainController', function($scope, $http) {
  $http.get('form.json').success(function(response) {
    $scope.result = response;
    console.log($scope.fields);
  });

  $http.get('form.json').success(function(response) {
    $scope.result = response;
    var fields = response.fields;
    $scope.richestClub = fields.answer.options[0].value;
    console.log($scope.richestClub);
    console.log($scope.fields);
  });
});

HTML

<my-form ng-app="CreateApp" ng-controller="mainController">

      <form ng-submit="userForm()" name="userForm" novalidate>
          <fieldset>
            <div ng-repeat="field in result.fields">
              <label for="{{field.type}}">{{field.label}}</label>

              <input ng-if="field.type != 'radio'"
                     name="{{field.name}}"
                     ng-required="{{field.required}}"
                     value="{{options.value}}" 
                     type="{{field.type}}" />

              <div ng-if="field.type == 'radio'">
                <div ng-repeat="option in field.options">

                  <input type="{{field.type}}"
                         name="{{field.name}}"
                         ng-required="{{field.required}}"
                         ng-model="richestClub"
                         value="{{option.value}}" />{{option.label}}
                </div>
              </div>

              <form-error ng-show="{{!!field.errorMessages.required}}">{{field.errorMessages.required}}</form-error>
              <form-error ng-show="{{!!field.errorMessages.invalid}}">{{field.errorMessages.invalid}}</form-error>
            </div>
          </fieldset>

         <button type="submit"
                 ng-disabled="userForm.$invalid"
                 ng-click="onSubmit(userForm)"> Submit </button>
        </form>

    </my-form>

Answer №1

  • First and foremost, the error that needs to be addressed is: fnPtr is not a function

To resolve this issue, it is important to define the functions userForm and onSubmit in the controller being used in HTML. Additionally, avoid naming the form the same as the ng-submit attribute.

For a demonstration without any errors in functionality, check out this Plunker demo

  • Once the form is ready, submit it to another simulated API endpoint that returns true or false. Can the AngularJS $http service be utilized for this purpose?

A suitable approach would be:

$http.post(url,data).then(function(response){
//your code here
})

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

The Angular Proxy seems to handle GET requests successfully, but encounters issues when it comes to

After setting up a proxy for my requests on my Angular application, I successfully managed to redirect my GET request to http://localhost:3000/api/users. However, the issue arises with my POST request as it continues to go to http://localhost:4200/api/user ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

Guide on automatically removing a DOM element in Jquery after a set amount of time

Is there a way to delete an HTML element after a specific period of time? If a certain condition is met before the allotted time, I want to pause the timer from deleting the element. Here's a snippet of code for reference: <ul> <li dat ...

Preloading images before loading a div using JavaScript

Can you walk me through implementing object first and then mergeObject in JavaScript? I have an interesting scenario where I need to display the original list followed by a merged list after a short delay. How can I achieve this using JavaScript? Specific ...

Beginning your journey with Mock server and Grunt

Although I have gone through the documentation available at , I am still struggling to get the mockserver up and running despite spending hours on following the instructions provided in the guide. Could someone please outline the precise steps or identify ...

Error: Uncaught [🍍]: The function "getActivePinia()" was invoked without an active Pinia instance present. Ensure that you have called "app.use(pinia)" before attempting to utilize a store

I encountered an issue while trying to access a store in Pinia for my Vue web application. Despite installing Pinia and setting app.use(createPinia()), I keep receiving the following error message: Uncaught Error: [ ...

I am unable to retrieve dynamic data from the database

Storing data in a MySQL database has been successful for me. I've been utilizing PDO in PHP to fetch the data and then converting it to JavaScript using json_encode. However, I keep encountering the output NaN when implementing a specific scenario. It ...

Utilize AngularJS's JSON datetime filter with user input

Here is the filter function I created to convert JSON date: app.filter("mydate", function () { var re = /\/Date\(([0-9]*)\)\//; return function (x) { var m = x.match(re); if (m) return new Date(parseInt(m[1])); else return ...

The Web API encountered an error while trying to serialize the response body for the specified content type

Working on an ASP.NET MVC 5 Web Api project. The application already has multiple APIs in place. Recently, I added a custom JsonConverter to handle date conversions based on timezone. public class CustomInfoConverter : JsonConverter { public overrid ...

Adding a specific element to an array using JQuery

I am in the process of developing a web application using jQuery to track goals and habits. Users can set a main goal such as 'Discipline' and then add sub-goals or habits related to that main goal (e.g. 'exercise every day'). Organizi ...

Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hard ...

External function's access to scope

Having an issue with the external function OnLoginFail when calling the function showFormAndHideMessage from it. I attempted to use: angular.element($("login")).scope().showFormAndHideMessage().$digest(); however, this approach did not yield any results ...

Why is my jQuery SlideReveal not displaying on page load?

Can anyone provide some help? I am currently using the jquery.slidereveal.js plugin from ''. The plugin works well when manually clicking the trigger to open and close the menu. However, I would like it to default to its last state on page load, ...

Can saving data within a mongoose pre-save hook initiate a continuous loop?

Currently, I am developing an API for a forum system which includes functionalities for users, forums, and posts. In my MongoDB Database, there is a 'categories' collection where each category acts as a container for a group of forums. Each categ ...

The inner workings of v8's fast object storage method

After exploring the answer to whether v8 rehashes when an object grows, I am intrigued by how v8 manages to store "fast" objects. According to the response: Fast mode for property access is significantly faster, but it requires knowledge of the object&ap ...

Having trouble with Socket.io sending data to a specific socketId?

I'm currently using Socket.Io 1.7.3 with Angular 2, connecting to a ExpressJS Server. I'm facing an issue where I am unable to send packages to a specific socket ID even though they are a match. Server code snippet: socket.on('subscribeNot ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...

Effortless Android JSON Decoding

Hey there, I'm new to android development and trying to figure out how to parse JSON in an android activity without using PHP. Instead, I am utilizing NODEJS on a server in AWS to generate my JSON data. I have a JSON object with values {"1":"Hello", ...

Sort through an array using criteria from another array

const items = [[{name:"p2"},{name:"p3"}, {name:"p7"},{name:"p9"},{name:"p1"}],[{name:"p6"}, {name:"p3"},{name:"p7"}, {name:"p9"},{name:"p2"}],[{name:"p ...

Creating a navigation bar that stays fixed at the top of

Hey there, currently I am utilizing a combination of jquery and css to affix my navigation menu at the top when scrolled. However, the problem is that my navigation menu is positioned beneath a div with a height set in viewport units (vh). The jquery scr ...