63

I am going through learning curve with AngularJs and I am finding that there are virtually no examples that serve real world use.

I am trying to get a clear understanding of how to submit a form with the most standard components and pass it on to a PHP file..

My fiddle.

Does anyone have any good examples on submitting simple, un-polluted, forms that would help me and probably numerous other Angularjs beginners..

When I say a clean form I am referring to something like this..

<div ng-app="myApp">

    <form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">

        First name:    <br/><input type="text" ng-model="form.firstname">    <br/><br/>
        Email Address: <br/><input type="text" ng-model="form.emailaddress"> <br/><br/>

        <textarea rows="3" cols="25" ng-model="form.textareacontent"></textarea>

            <br/><br/>

        <input type="radio" ng-model="form.gender" value="female" />Female ...
        <input type="radio" ng-model="form.gender" value="male" />Male <br/>

            <br/><br/>

        <input type="checkbox" ng-model="form.member" value="5"/> Already a member

            <br/><br/>

        <input type="file" ng-model="form.file_profile" id="file_profile"><br/>
        <input type="file" ng-model="form.file_avatar" id="file_avatar">

            <br/><br/>

        <!-- <button ng-click="save()" >Save</button> -->
        <input type="submit" ngClick="Submit" >

    </form>

</div>

My ng-app code...

var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {

     var formData = {
        firstname: "default",
        emailaddress: "default",
        textareacontent: "default",
        gender: "default",
        member: false,
        file_profile: "default",
        file_avatar: "default"
    };

    $scope.save = function() {
        formData = $scope.form;
    };

    $scope.submitForm = function() {
        console.log("posting data....");
        formData = $scope.form;
        console.log(formData);
        //$http.post('form.php', JSON.stringify(data)).success(function(){/*success callback*/});
    };

 });

I guess three questions I have from here on are...

  1. How is my php file supposed to interact with this (how to I get the json string to an array in php file)?
  2. How would I submit value of a checkbox when the checkbox is true?
  3. I find a lot of information abotu using jQuery with Angular to submit images,, I see there is an image object in this submission already,, how do I retrieve that data? What are considerations to include with images?

I am willing to take any clear and concise information and assemble a good learning example for everyone...

My fiddle

Vidya Sagar
  • 1,699
  • 3
  • 17
  • 28
GRowing
  • 4,629
  • 13
  • 52
  • 75
  • Here is a somewhat related blog article that I thought did an effective job of explaining some basic AngularJS and HTML form interaction: http://www.thebhwgroup.com/blog/2014/08/designing-html-forms-angularjs-part-1/. It does not cover the submitting part of your question as much, but is a great foundation for getting there. – PFranchise Aug 15 '14 at 20:21

5 Answers5

26

WARNING This is for Angular 1.x

If you are looking for Angular (v2+, currently version 8), try this answer or the official guide.


ORIGINAL ANSWER

I have rewritten your JS fiddle here: http://jsfiddle.net/YGQT9/

<div ng-app="myApp">

    <form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">

        First name:    <br/><input type="text" name="form.firstname">    
        <br/><br/>

        Email Address: <br/><input type="text" ng-model="form.emailaddress"> 
        <br/><br/>

        <textarea rows="3" cols="25">
          Describe your reason for submitting this form ... 
        </textarea> 
        <br/>

        <input type="radio" ng-model="form.gender" value="female" />Female
        <input type="radio" ng-model="form.gender" value="male" />Male 
        <br/><br/>

        <input type="checkbox" ng-model="form.member" value="true"/> Already a member
        <input type="checkbox" ng-model="form.member" value="false"/> Not a member
        <br/>

        <input type="file" ng-model="form.file_profile" id="file_profile">
        <br/>

        <input type="file" ng-model="form.file_avatar" id="file_avatar">
        <br/><br/>

        <input type="submit">
    </form>
</div>

Here I'm using lots of angular directives(ng-controller, ng-model, ng-submit) where you were using basic html form submission. Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission

BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.

For general advice on angular form submission see the cookbook examples

UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission

The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.

Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.

caffeinated.tech
  • 6,428
  • 1
  • 21
  • 40
  • 1
    This is excellent. Thanks! If I may ask, is there a particular reason why you omitted the text-area? Am I correct to presume that the image upload is more complex? From what I find around the web, many people suggest using jQuery in combination with ng-js. – GRowing Nov 14 '13 at 20:24
  • Ah, no I left out the text area by mistake. Yes for the image upload you will need to use the ng-upload, I have never used it before but there is a nice post on SO: http://stackoverflow.com/questions/17216806/angularjs-uploading-an-image-with-ng-upload. – caffeinated.tech Nov 14 '13 at 23:48
  • Jquery and Angular do similar things in very different ways. Use it when you absolutely need it( eg. I'm using the HighCharts.js chart library which depends on JQ, and there aren't many alternative graphing solutions available). If you are used to developing in JQ, try to find the angular way to do things first before having to resort to JQ. – caffeinated.tech Nov 14 '13 at 23:49
  • Thanks LcLk. I was being little puzzled with using them both. Currently I will focus on mastering ng as much as possible as if I have never seen jQuery before – GRowing Nov 15 '13 at 16:00
  • In the JSFiddle, shouldn't that be $scope.form instead of $scope.data? – Nayeem Zen Mar 10 '15 at 03:29
4

Sending data to some service page.

<form class="form-horizontal" role="form" ng-submit="submit_form()">
    <input type="text" name="user_id" ng-model = "formAdata.user_id">
    <input type="text" id="name" name="name" ng-model = "formAdata.name">
</form>

$scope.submit_form = function()
            {
                $http({
                        url: "http://localhost/services/test.php",
                        method: "POST",
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        data: $.param($scope.formAdata)
                    }).success(function(data, status, headers, config) {
                        $scope.status = status;
                    }).error(function(data, status, headers, config) {
                        $scope.status = status;
                    });
            }
Akhilesh Kumar
  • 849
  • 1
  • 15
  • 28
2

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

Angularjs - Form Post Data Not Posted?

The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

Community
  • 1
  • 1
GRowing
  • 4,629
  • 13
  • 52
  • 75
1

I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().

If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.

D.S
  • 1,110
  • 3
  • 11
  • 26
  • I am not talking about standard form submissions either. I am working on a project that will require countless xhr requests and what I am referring to are stable ways of passing information from the DOM to the back-end. If you wish to share code, please, feel free. I am aware of the two way binding. – GRowing Nov 20 '13 at 07:47
  • Also.. I am looking for good examples of passing data as json from backend to ng-js scopes.. – GRowing Nov 20 '13 at 07:49
1

var app = angular.module( "myApp", [] );

app.controller( "myCtrl", ["$scope", function($scope) {

    $scope.submit_form = function(formData) {

        $scope.formData = formData;

        console.log(formData); // object
        console.log(JSON.stringify(formData)); // string

        $scope.form = {}; // clear ng-model form

    }

}] );
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

    <form ng-submit="submit_form(form)" >

        Firstname: <input type="text" ng-model="form.firstname" /><br />
        Lastname: <input type="text" ng-model="form.lastname" /><br />

        <hr />

        <input type="submit" value="Submit" />

    </form>

    <hr />          

    <p>Firstname: {{ form.firstname }}</p>
    <p>Lastname: {{ form.lastname }}</p>

    <pre>Submit Form: {{ formData }} </pre>

</div>

Codepen

antelove
  • 3,216
  • 26
  • 20