Leveraging AngularJS to send a post request to the server through the $http

Can't seem to find a solution to my Angular issue, despite searching for it extensively?

After starting to learn Angular recently, I've put together the following code based on various online resources.

Here's the HTML:

<div data-ng-app="appAuthentication">

    <form name="authentication" method="post" data-ng-controller="AuthenticationController" data-ng-submit="doAuthentication(authentication)" novalidate>

        <fieldset>

            <label for="sign-in-email-address">Email address:</label>
            <input id="sign-in-email-address" name="sign-in-email-address" data-ng-model="authentication.emailAddress" type="text" required />

            <label for="sign-in-password">Password:</label>
            <input id="sign-in-password" name="sign-in-password" data-ng-model="authentication.password" type="password" required />

            <button type="submit">Go &#187;</button>

        </fieldset>

    </form>

</div>

And here is my Angular script:

angular.module('appAuthentication', [])

    .controller('AuthenticationController', ['$scope', function($scope, $http) {

        $scope.authentication = {
            emailAddress: '',
            password: ''
        };

        $scope.doAuthentication = function(authentication) {

            // console.log('Hello ' + authentication.emailAddress);

            $http({
                method : 'POST',
                url : '/actions/authentication/sign-in.php',
                data : authentication.emailAddress
            })
            .success(function () {
                console.log('Success');
            })
            .error(function () {
                console.log('Failure');
            });

        };

    }]);

The error message in the console reads as follows:

TypeError: undefined is not a function
    at k.$scope.doAuthentication (http://cms2.indypub.co.uk/static/scripts/core.js:16:4)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:176:88
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:193:165
    at k.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:111:373)
    at k.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:112:121)
    at HTMLFormElement.<anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:193:147)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:31:161
    at q (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:7:290)
    at HTMLFormElement.c (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:31:143) 

Once I uncomment the initial console.log statement in the JavaScript file, the emailAddress is displayed in the console log.

If you have any insights into where I might be making a mistake, I would greatly appreciate your feedback.

Thank you,

Tony.

Answer №1

The primary issue lies within your controller dependencies - specifically, you have included $http in the function parameter without adding it to the array notation.

Modify:

controller('AuthenticationController', ['$scope', function($scope, $http) {
  // your code
});

to

controller('AuthenticationController', ['$scope', '$http', function($scope, $http) { 
  // your code
});

Additionally, adjust the value attributes of your name in the input tags to resemble a variable name - as these names will be utilized when validating forms.

For example:

<form name>.<input name>.$pristine
or
<form name>.<input name>.$error

Adjust:

    <label for="sign-in-email-address">Email address:</label>
    <input id="sign-in-email-address" name="sign-in-email-address" data-ng-model="authentication.emailAddress" type="text" required />

    <label for="sign-in-password">Password:</label>
    <input id="sign-in-password" name="sign-in-password" data-ng-model="authentication.password" type="password" required />

to:

    <label for="sign-in-email-address">Email address:</label>
    <input id="sign-in-email-address" name="sigInEmailAddress" data-ng-model="authentication.emailAddress" type="text" required />

    <label for="sign-in-password">Password:</label>
    <input id="sign-in-password" name="signInPassword" data-ng-model="authentication.password" type="password" required />

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

What order does JavaScript async code get executed in?

Take a look at the angular code below: // 1. var value = 0; // 2. value = 1; $http.get('some_url') .then(function() { // 3. value = 2; }) .catch(function(){}) // 4. value = 3 // 5. value = 4 // 6. $http.get('some_url') ...

JavaScript promise will return a value that is undefined

Trying to pass a jQuery ajax request through a promise like this: var foo; foo = bar().then(function(response) { console.log("Success!", response); console.log(foo[0].bool); }, function(error) { console.error("Failed!", error); }); console.lo ...

Handling errors in XMLHttpRequest using Axios in React JS

I am currently utilizing the REACT-JS framework for my FRONT-END development: Below is the action I am calling from REDUX-REACT export function UserLogin(values) { var headers = { 'Access-Control-Allow-Origin': '*', ...

Transmit information to the server

Currently, I am in the process of creating an iPhone app. My goal is to utilize JavaScript to send longitude and latitude values retrieved from the phone to a server for the purpose of initiating a search function. Should I familiarize myself with cross-do ...

What are the steps to send AJAX data before closing the page?

Trying for over 7 hours to send a value to the database when the user closes the page, like online and offline. Still struggling to find a working solution. <script tysssspe="text/javascript"> //ST window.onbeforeunload = function(){ var user_st = ...

Meta tag information from Next.js not displaying properly on social media posts

After implementing meta tags using Next.js's built-in Head component, I encountered an issue where the meta tag details were not showing when sharing my link on Facebook. Below is the code snippet I used: I included the following meta tags in my inde ...

Quick method for handling arrays to generate waveforms

I'm currently working on optimizing the code for my web application. While it functions, the performance is a bit slow and I am looking to make improvements: The main concepts behind the code are: The function retrieves the current buffer and conve ...

How can I temporarily turn off the animation on a directive in Angular JS to prevent it from animating during page load?

Check out this JSFiddle for the issue: http://jsfiddle.net/goodwill/ezNuj/ I have created a custom directive with the code below: myApp.directive('ngFadeIn', function() { return function(scope, element, attr) { if (element.is('tr, t ...

AngularJS: Optimizing Image Loading for the Initial Page Load in AngularJS

Currently, I am working with a JSON object that contains image URLs which I am displaying using ng-repeat. However, I have encountered an issue where the images flicker when the page loads for the first time. I am looking to implement a preloader (CSS spin ...

knockout, loop within a loop

Imagine I have a group of Humans who own Cats, and those Cats have Kittens class Person { String name; Cat[] cats; } class Cat { String name; Kitten[] kittens; } class Kitten { String name; } Now I want to display all my Kittens with ...

Tips for establishing control when retrieving the JSON information

I have encountered a challenge while developing a currency converter application. The issue I am facing is related to the order of data. My app fetches information from two JSON files - one containing prices and the other containing full names of currencie ...

What is the best way to apply a filter to an optional property value only when it is present?

I have JSON data like this: { "message": "hi" } However, the format could also be like this: { "message": { "action": "foo" } } My goal is to remove any records where message.action == "foo" I ...

Transforming protobufs into JSON using C++

Trying to link data from protobuf to JSON has been quite the task. Here are the key parts of my code: Message* m; std::string json; std::string binary_s; ...populating the message... m->serializeToString(&binary_s); MessageToJsonString(*m, &js ...

Unlocking JSON data in Grails 2.0: A step-by-step guide

When using jQuery, I send JSON data to a controller like this: $.ajax ({ type: "POST", url: 'http://localhost:8080/myproject/myController/myAction', dataType: 'json', async: false, //json object to sent to the authentication ...

Encountering an issue with Angular 5.2 application build on VSTS build server: Running into "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" error

Out of nowhere, the builds began failing with the following error : 2019-01-03T12:57:22.2223175Z EXEC : FATAL error : CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error MSB3073: The command "node node_modules/webpack/bin/w ...

Is it possible to encounter an invalid character when trying to parse valid JSON using

I have an object with properties that contain JSON strings. When I serialize this object, I get the following string: [{ "template": 1, "action_json": "{\"id\":\"1\",\"action\":\"An action for all of IT!\",& ...

The functionality of a pop-up window is not compatible with Google Maps

I recently implemented a script on my webpage that triggers a popup window every time the page is loaded. Here's how the script looks: <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>ColorBox de ...

Guide on setting a v-model within a v-for loop (using an example from Bootstrap Vue)

Currently, I am utilizing vue-bootstrap for creating input fields using a v-for directive. The objective is quite similar to the example provided in this link. However, I am encountering some difficulties in obtaining the data collected from these inputs i ...

Update View Not Reflecting React State Increment

Here is the code snippet I am currently working with: class PickColor extends React.Component { constructor(props) { super(props); this.state = { active: 0 } this.setState = this.setState.bind(this); } ...

The integration of socket.io with static file routing in node.js is encountering issues

I am currently developing a chat application and I have encountered an issue. When the static file routing is functioning correctly, the socket.io for the chat feature throws a "not found" error in the console. http://localhost/socket.io/?EIO=3&tran ...