Angular JS Post Data – Submitting AJAX Forms

Angular JS Post Data – Submitting AJAX Forms

Introduction

There are different ways to submit forms; it varies based on different scenarios. In this blog, we shall see how to submit a form in Angular rather than old PHP method.

We will look at processing a form with just plain jQuery. This process is done primarily in the javascript. We will submit the form, show errors, add error classes, and show/hide messages in javascript. We shall use Angular, after the above mentioned process, thus making the bulk of work seem much simpler.

Use Case

The use case is a well-known simple web form submission with basic input fields name and email. This use case is used to explain the different ways of submitting forms (PHP method and Angular method).pic 1

Form Requirements:

  • Process the form without page refresh
  • Enter Name and Email
  • Show errors, if any
  • Turn inputs red, if errors are found
  • Show success message, if all is good

Solution

Before solving our use case, let’s get some pre-requisites satisfied. Fortunately, Ajax needs only couple of files to start with, for submission.

Pre-requisites:

  • XAMPP
  • index.html
  • process.php

Processing the form:

Let’s setup the PHP to process our form. This will be very minimal, so we can use http POST to get the form data.

This is an example of a very simple form processing script. We only check if the data exists. If it exists, don’t do anything. If it does not, then add a message to our $errors array.
To return processed data to an AJAX call, we have to echo and json_encode. This is all we have to do with our PHP form processing. It will be the same for processing a form using normal jQuery AJAX or Angular.

Showing the Form:

Let’s create our HTML that will show our form.

Now we have our form. We’ve also used Bootstrap plugin to make it look better. Using the Bootstrap syntax, we have also created a spot under each input to show a line of text for our errors.

pic 2

Submit the form with jQuery:

Let’s go through the process of submitting the form with jQuery now. We will add all the code into our empty <script> tag under the head section.

This involves quite a lot of code to process the form. We have codes to get the variables from the form, send it to our form using AJAX, check if there are any errors, and show a success message. Above all, every time the form is submitted we have to clear the past errors.

pic 3

On successful submission:

pic 4

Submit the Form with Angular:

Now we will look at the same form, submitted with Angular. Remember, we don’t have to change anything in the process of a PHP form because our application will operate the same way (showing errors and successes in the same places).

We are going to set up our Angular application right inside the <script> tags we used earlier. So we have to delete everything inside the <script> tags. Let’s begin once it’s done.

  • Setting up an Angular Application:

The steps to set up our Angular application are:

    • Load angular
    • Set up a module
    • Set up controller
    • Apply module and controller to HTML
    • Set up 2-way bound variables
    • Set up errors and messages

It sounds like a lot, but in the end, we have used less code and it is much cleaner. It is also much easier to create larger forms with many inputs.

  • Angular Module and Controller:

Let’s load the Angular library and create our module and controller.

We now have the foundation for our Angular app. We’ve loaded Angular, created a module and controller, and applied it to our site.

Next we will be showing off how 2-way binding works.

  • 2-Way Data-Binding:

The steps to set up our Angular application are:

This is one of the core ideas of Angular and very powerful. From the Angular docs: “Data-binding in Angular web apps is the automatic synchronization of data between the model and view.” This means that the step where we have to grab data from the form using$(‘input[name=name]‘).val() is not required.

We bind data to a variable in Angular, and whenever it changes in either the Javascript or in the view, it changes in both.
To demonstrate data-binding, we’ll get our form inputs to populate a variable formData automatically. Let’s look back at our Angular controller which we applied to our page. We have passed in$scope and $http.

    • $scope:  can be described as the glue between application controller and the view. Basically variables are passed to and from our controller and viewed using $scope. For a more detailed definition, check out the docs.
    • $http: The Angular services that will help us do our POST request. For more information, check out the docs.
  • Getting the Variables Using Data-Binding

Let’s apply this information to our form. Its way simpler than it sounded above. We will add a line to the Angular controller and a line to the view.

 Now we have set up a formData object. Let’s populate it with our form inputs. Before we had to explicitly call each input and get its val(). Not anymore. We can use ng-model to bind a specific input to a variable.

 Now, Angular will know that each input is bound to formData. As we type into each input box, we can see the formData object being populated! It’s magic!

Note: No need to use the word $scope in the view. Everything is considered to be nested inside of $scope.

  • Processing the Form:

In our old form, we have used jQuery to submit the form using $(‘form’). submit(). Now we shall use an Angular feature called ng-submit. To do this, we should add a controller function to process the form, and tell our form to use that controller function.

Our form knows to use controller function when it is submitted. Now that we have that in place, let’s actually process the form using $http.

The syntax for processing a form will look very similar to the original way of doing it. The benefit is that we don’t have to grab our form data manually, or inject, hide, or add classes to show errors or success messages.

That’s it for our form! We don’t have to add or remove classes. We don’t have to clear the errors every time we submit the form. We just have to bind the variables and the view will take care of the rest. This is great since the controller is for the data and the view is for showing the data.

Note: jQuery POST vs Angular POST Sometimes we may see that our POST isn’t showing data on the server. This is because of the difference in the way jQuery and Angular serialize and sends data. This comes down to the server language we are using and its ability to understand Angular’s data.

The above code is for a PHP server, and jQuery is needed to execute the $.param function. There are ways to do it without jQuery but that’s pretty much the only reason jQuery was included in this example, because it is easy to execute.

The below cleaner syntax will work based on our server-side language. For more information on making AngularJS AJAX calls, read this article: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

  • Cleaner Syntax:

This example sends data as a string and sets our headers. If we don’t want to do that kind of stuff and just want the cleanest Angular $http POST possible, then we shall use the shorthand method:

 Note: $http inside controllers: Ideally, we would move the $http request outside of the controller and into a service. This is just for demonstration purposes and so we will do a write-up on services soon.

  • Showing the Errors and Messages in the View:

We will use the directive ng-show and ng-class to handle our view. The Angular double brackets will place our variables where we need them also.

  • ng-show: Show or hide an element based on if a variable exists.
  • ng-class: Add or remove a class based on if a variable exists (or some other expression).
Our form is done! By using the power of Angular, we can move all unwanted show/hide logic out of our javascript and into the view. Now our javascript file is free to just handle data and our view can do its thing.In our classes , errors and success messages will hide and show respectively, if they are available. This is so much easier since we don’t have to worry, if we have covered everything in our old javascript. We don’t have to hide those error messages on every form that is submitted.

Conclusion

Now we have our form fully converted to Angular. We’ve gone through a lot of concepts and hopefully as we play with them more, they will be easier to use.

We’ve gone through:

  • Creating an Angular module
  • Creating an Angular controller
  • 2-way data-binding
  • ng-model to bind inputs
  • ng-click to submit a form
  • Showing form errors using 2-way data-binding
  • Showing a div based on if a variable exists
  • Adding a class based on if a variable exists

These Angular techniques will carry over into much larger applications and there are many great things that we can build.

References

18047 Views 5 Views Today
  • li

    If I am submitting without entering any field and while checking using firebug tool. POST is coming empty. I am not seeing the field name. It is not showing the submit value also. I hvae multiple form in a page based on the submit different action has to happen. So I need the button name in post

    • http://www.treselle.com/ Treselle Systems Blog

      It might be the case of the form data not binding to the model. So please try adding ng-model to the form-input fields. like,