AngularJS AJAX POST with parameters

AngularJS is awesome. I am loving it. But the documentation is not that great (It is in the MSDN state right now). It took me an hour to figure out the usage of $http for submitting an HTML form asynchronously.

I thought it would be useful to know the exact usage along with an example. To proceed, you’ll need to know the basics of HTML forms, JavaScript and PHP

To help speed up, you can download the source code used here. Now we know how to use HTML forms and use the normal HTML form attributes like action and method which help you submit the form contents to a file on a server.

So, we are submitting the input in this form to a file named server.php which resides on the server. Without using any external JavaScript library, this is how we would do it.

File: usual.htm

<html>
    <head>
        <title>Usual POST Demo</title>
    </head>
    <body>
        <form name="formWho" action="getLength.php" method="POST">
            <input type="text" name="txtName" placeholder="Enter Name" />
            <input type="submit" />
        </form>
    </body>
</html>

File: getLength.php

<?php
if(isset($_POST["txtName"]) && is_string($_POST["txtName"]))
{
    echo strlen($_POST["txtName"]);
}
else
{
    echo "-1";
}

This sends a POST request to the file. No AJAX in this case.

To send an AJAX request using AngularJS, firstly we need to add a controller. The controller is a JavaScript function which handles all the events/requests from a particular HTML element. We can chose that HTML element by adding to it the ng-controller attribute.

<form name="formWho" action="getLength.php" method="POST"> becomes <form ng-controller="myController">

We will be binding the input values to a model instead of binding it to the name of the HTML element. Hence, we replace name="txtName" by ng-model="user.txtName" Having done this, we can access (and modify) the value in the input box using the model name user.txtName

<input type="text" name="txtName" placeholder="Enter Name" /> becomes <input type="text" ng-model="user.txtName" placeholder="Enter Name" />

In this example, we are fetching the length of the string in the input box and thus I have named the actionHandler as funcGetLength. This is the javascript function we want to execute when this button is clicked. We will add the ng-click attribute.

<input type="submit" /> becomes <input ng-click="funcGetLength()" type="button" value="Submit" />

Since are using AngularJS, we will need to include the AngularJS library in our page. To do that, we will add the following script tag inside the head section in our HTML.

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

After making the above changes to the initial HTML file, we get the following – let’s call it angular.html. This is our HTML page.

File: angular.htm

<html ng-app>
    <head>
        <title>AngularJS POST Demo</title>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
        <script type="text/javascript" src="controller.js"></script>
    </head>
    <body>
        <form ng-controller="myController">
            <input type="text" ng-model="user.txtName" placeholder="Enter Name" />
            <input ng-click="funcGetLength()" type="button" value="Submit" />
        </form>
    </body>
</html>

Now we go ahead and write a Controller – a JavaScript function object responsible for doing the needful after we click on the button. We have added the attributes – ng-controller, ng-model, ng-click. Now is the time to define them in a JavaScript file. I am calling it controller.js.

File: controller.js

function myController($scope, $http)
{
    $scope.user = {txtName:"default value"};
    $scope.funcGetLength = function()
    {
        $http.post(
            "getLength.php",
            $.param($scope.user),
            {
                headers:
                {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            })
            .success(function(responseData)
            {
                alert("Length is " + responseData);
            });
    };
}

The controller is responsible for the events triggered inside the element which declares the controller. In this case, it is the form element. $scope.user is the JSON object which would take values from the model. Inside the controller, $scope.user = {txtName:"default value"} gives default values to the variables in the model. The other stuff is pretty much self explanatory. EXCEPT for the parameter handling.

In the $http.post call, the second argument is params. There are multiple ways to do it. We’ll discuss the easiest way – using jQuery. Since AngularJS provides an easy way to put the form contents into one JSON object, why not just send the same object as the params argument? It’s not as easy as that. We need to serialize the JSON object to a URL query string before passing it to $http.post.

AngularJS depends on jQuery for some of its features. So, it is advisable to include jQuery along with AngularJS in your pages.

Now that we have jQuery to help us, we can use $.param function from jQuery to serialize the JSON object into a query string which can be passed as params.

Some things we should know, because debugging JavaScript is not easy!

  • You may not always want a default value in the input box, it still makes sense to provide a default value (may it be a blank string) because if the user does not change the value inside the input box, the value submitted is JavaScript’s undefined instead of the conventional blank string.
  • Setting the Content-Type in the header is NECESSARY because the default Content-Type for $http.post is application/json! There is a way to provide a default Content-Type to be used for all requests, you can use that too.

You can download the example as a zip file from here. Hope it was helpful. :)

2 thoughts on “AngularJS AJAX POST with parameters

  1. Bluemoon

    The example has an extra js file – controller_jQuery.js. It is not used anywhere.
    What is it for?

    Reply
    1. Sagar Post author

      Sorry for not mentioning about it in the blog.
      If you have jQuery in your page, you should use controller_jQuery.js.
      It uses the $.param function from jQuery for serializing request parameters.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha