Is there a method in AngularJS to submit form data when the input fields are pre-populated using a GET request?

How do I submit form data in AngularJS? I have a div that populates the input field from a GET request. Now, I want to send this data using a POST method. How can I achieve this? Below is the form div:

<div class="row" ng-app="myApp" ng-controller="myCtrl">
    <div class="col-lg-4">
        <span>{{myMessage}}</span>
        <form name="userForm" ng-submit="submitForm()">
            <div class="form-group">
                <label>Make</label>
                <input type="text" class="form-control" id="makeid"  ng-model="myMessage.make">
                </div>
                <div class="form-group">
                    <label>Vin</label>
                    <input type="text" class="form-control" id="vinid" ng-model="myMessage.vin">
                    </div>
                    <div class="form-group">
                        <label>Modal</label>
                        <input type="text" class="form-control" id="modalid" ng-model="myMessage.model">
                        </div>
                        <div class="form-group" ng-repeat="part in myMessage.parts">
                            <label>Parts</label>
                            <input type="text" class="form-control" id="partsid" ng-model="part.name">
                                <input type="text" class="form-control" id="partsid" ng-model="part.desc">
                                </div>
                                <button type="submit" class="btn btn-primary" onclick="sendData()">Submit</button>
                            </form>
                        </div>
                    </div>

I attempted to post this data at a specific URL:

<script>
function sendData($scope) {
    $http({
        url: 'http://192.16.1.1:8080/restproj/v1/dealer/car',
        method: "POST",
        data: { 'message' : message }
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });
}
</script>

However, I am struggling to successfully post it. What other methods can I use to send the data?

Answer №1

It seems like you're looking for code similar to this:

                $http({
                    url: 'http://192.16.1.1:8080/restproj/v1/dealer/car',
                    method: "POST",
                    data: { 'message' : $scope.myMessage}
                })

Answer №2

Remove the onSubmit attribute from the button element. Instead, define a submitForm function in your controller.

        app.controller('myCtrl', function ($scope, $http) 
        { 

            $scope.submitForm= function () {
                var message = $scope.myMessage   
                $http.post('http://192.16.1.1:8080/restproj/v1/dealer/car',message).then(function (response) {

 }, 
    function (error) {
                    console.log(error);
                                    });
            } 
        });

Answer №3

When working with AngularJS, it is advised not to use the onclick attribute. Instead, utilize the ng-submit or ng-click directives for better functionality.

<div class="row" ng-app="myApp" ng-controller="myCtrl">
    <span>{{myMessage}}</span>
    <form name="userForm" ng-submit="submitForm()">
        <label>Make</label>
        <input type="text" id="makeid" ng-model="myMessage.make">
        <label>Vin</label>
        <input type="text" id="vinid" ng-model="myMessage.vin">
        <label>Modal</label>
        <input type="text" id="modalid" ng-model="myMessage.model">
        <div ng-repeat="part in myMessage.parts">
            <label>Parts</label>
            <input type="text" ng-model="part.name">
            <input type="text" ng-model="part.desc">
        </div>
        <button type="submit">Submit</button>
    </form>
</div>

In the controller:

$scope.submitForm = function submitForm() {
    $http({
        url: 'http://192.16.1.1:8080/restproj/v1/dealer/car',
        method: "POST",
        data: $scope.myMessage
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });
}

For further details, refer to the AngularJS Developer Guide -- Forms

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

Update state within React components without impacting any other state variables

Imagine I have an object structured like this: person : { name : "Test", surname : "Test", age : 40, salary : 5000 currency : "dollar", currency_sign : "$", . . . } I am looking to achieve the following I will make ...

I am uncertain about how to interpret this method signature

Can you help me determine the correct method signature for handleError? The linter tslint is indicating an error message that says expected call-signature: 'handleError' to have a typedef (typedef). Here is the code snippet in question: import ...

Guide on verifying internet connection status using Ajax request

Ensuring authentication by checking the availability of network connection on mobile devices. To do this, we must have both a username and password. The authentication process will be conducted online, requiring an active internet connection on the device. ...

Error code 302 is triggered when attempting to retrieve an HTML file from a web address

I'm having trouble retrieving the HTML document from the URL provided below: The issue is that I keep getting a 302 response code! I am not very familiar with how this request is being handled (with the function and parameters), so I am unsure of the ...

Utilizing Grunt bake to generate unique files with various content from a single template

Is it possible to use bake to display multiple contents within the same styled template? https://github.com/MathiasPaumgarten/grunt-bake For example, if my template looks like this: <div style="background-color:red"> </div> And I have Cont ...

Error 404 - The Web API is missing and needs to be integrated with AngularJS

Here is the controller code snippet: [HttpGet] [ActionName("Email")] public HttpResponseMessage GetByEmail(string email) { Users user = db.Users.Find(email); if (user == null) { throw new HttpResponseExcept ...

What causes the element to remain visible despite the changes made to the v-show attribute?

<!DOCTYPE html> <html> <head> <title>test</title> <script src="https://unpkg.com/vue"></script> </head> <body> <div id="app"> <p v-show="show&qu ...

The issue of resolving NestJs ParseEnumPipe

I'm currently using the NestJs framework (which I absolutely adore) and I need to validate incoming data against an Enum in Typscript. Here's what I have: enum ProductAction { PURCHASE = 'PURCHASE', } @Patch('products/:uuid&apos ...

Web fonts are functioning properly only on Chrome and Safari for Macintosh operating systems

A web designer provided me with some fonts to use on a website. Below is the content of my fonts.css file: /* Font Awesome */ /* Font Awesome Bold */ @font-face{ font-family: 'font-awesome'; src: url('fonts/font-awesome-bold-webf ...

Automatically update the page when there is a change in the status of the

$counter = "SELECT countnumber FROM onairsystem WHERE id='1'"; $counterresult = $connection->query($counter); $rows = $counterresult->fetch_array(); $number = $rows['countnumber']; Is there a way to automatically refresh the we ...

Preventing Redundancy: Handling duplicate jQuery validator error messages in dynamically loaded content

Recently, I encountered an issue while loading a partial page (MVC) through jquery ajax. The partial page that loads contains a form which requires validation using jquery validator. Interestingly, the form needs to be parsed again after dynamic elements ...

Can you explain the concept of "excluded" in relation to project subdirectories on Webstorm?

When using Webstorm, you have the option to mark project subdirectories as "excluded". However, the full implications of this designation remain unclear in the Webstorm documentation. Does marking a directory as excluded impact debugging or deployment proc ...

Having trouble with fs.readFile in Node.JS on Ubuntu?

Currently, I am facing an issue when trying to read XML files. Strangely, the code works flawlessly on my personal computer running OS X. However, when I run the same code on a DigitalOcean Ubuntu 16 Server, it fails to produce any results. I am utilizing ...

I am looking to manage the error handling service, and my next step is to intentionally insert a single error into my service and have it automated

Need help with error handling in my service. I want to manually insert a single error, but would like it to be done automatically instead. 'use strict'; angular.module('nexoolApp.errorservice', ['nexoolApp.config']) .servic ...

Ways to eliminate unused classes from JQuery UI

We have successfully implemented JQuery UI library for enhancing our interface. However, since we no longer need to support outdated browsers like IE6, classes such as .ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl are unnecessary and clu ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Issue: Encounter an Error with Status Code 401 using Axios in React.js

For my login page, I am utilizing a combination of Laravel API and ReactJS frontend. In my ReactJS code, I am using Axios to handle the parsing of the username (email) and password. The login API endpoint is specified as http://127.0.0.1:8000/api/login, wh ...

Unable to save data in local storage

I'm enhancing an existing chrome extension while ensuring a consistent style. I am looking to implement a new feature, and I have written a script that saves the user's selection from the popup and sets a new popup based on that choice going forw ...

The design problem arises from using jQuery to dynamically prepare the table body at runtime

The table row and data are not appearing in the correct format. Here is a link to the problem on Fiddle: http://jsfiddle.net/otc056L9/ Below is the HTML code: <table border="1" style="width: 100%" class="eventtable"> <thead style="color: b ...

Utilizing Vue JS to showcase a pop-up block when hovering over a specific image

There are four images displayed, and when you hover over each one, different content appears. For example, hovering over the first image reveals a green block, while hovering over the second image reveals a blue block. However, the current logic in place i ...