Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS POST to Server

Tags:

angularjs

I have an angularJS form which posts data to a Java Servlet, but I am not seeing the request go through; servlet "create" wasn't called.

Here's my code:

test.html

<body>
    <form ng-controller="UserController">

        <legend>Create User</legend>
        <label>Name</label> 
        <input type="text" id="name" name="name" ng-model="name" placeholder="User Name"> 

        <label>Email</label>
        <input type="text" id="email" name="email" ng-model="email" placeholder="ur email here"> 

        <label>Password</label>
        <input type="text" id="pwd" name="pwd" ng-model="pwd" placeholder="ur own pwd here">

        <button ng-submit="createUser()" class="btn btn-primary">Register</button>

    </form>
</body>

script.js

function UserController($scope, $http) {
    $scope.user = {};
    $scope.createUser = function() {
        $http({
            method : 'POST',
            url : '/create',
            data : 'name=' + $scope.user.name + '&email=' + $scope.user.email,
            headers : {
                'Content-Type' : 'application/x-www-form-urlencoded'
            }
        })
    }

my servlet is as below,but it doesn't print "Post" an all.

public class FirstServlet extends HttpServlet
{

    /**
     * 
     */
    private static final long   serialVersionUID    = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        System.out.println("Get");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        System.out.println("Post");
    }
}

The web server is jetty,and the web.xml as below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    version="2.4"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
        <servlet-name>createUser</servlet-name>
        <servlet-class>servlet.FirstServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>createUser</servlet-name>
        <url-pattern>/create</url-pattern>
    </servlet-mapping>
</web-app>
like image 891
yxdming Avatar asked Feb 24 '13 01:02

yxdming


People also ask

What is HTTP post in AngularJS?

AngularJS Http Post ($http. POST() services are used to send the data to a specific URL and expects the resource at that URL to handle the request that means we can say that POST method is used to Insert new data based on given URL and it is one of the shortcut method in $http service.

What is Httpservice in angular?

The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP. For unit testing applications that use $http service, see $httpBackend mock.

How do we pass data and get data using http in angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.


1 Answers

To post data to a web server, you will want to bind your form values to a object in the $scope, and then submit that object to the script.

The trick is to submit the entire object "user" to the server, and Angular will automatically format it in JSON. Also, "user" was not being used by the ng-model tags.

Another thing to note is that you will probably want to include something for the app to do when it finishes the request. You can use the methods ".success(function(data){})" and ".error(...)" to do this (these are methods on the promise $http returns).

I've included both PHP and Servlet code; it is the same, however, for all server scripts (JSON data from Angular).

HTML

<body>
<form ng-controller="UserController" ng-submit="createUser()">

    <legend>Create User</legend>

    <label>Name</label> 
    <input type="text" id="name" name="name" ng-model="user.name" placeholder="User Name"> 

    <label>Email</label>
    <input type="text" id="email" name="email" ng-model="user.email" placeholder="ur email here"> 

    <label>Password</label>
    <input type="text" id="pwd" name="pwd" ng-model="user.pwd" placeholder="ur own pwd here">

    <button class="btn btn-primary">Register</button>

</form>
</body>

</html>

Controller

function UserController($scope, $http) {
    $scope.user = {};
    $scope.createUser = function() {
        $http({
            method : 'POST',
            url : '/create',
            data : $scope.user
        })
    }

Example Server Code: PHP

$data = file_get_contents("php://input");
$objData = json_decode($data);

$pwd = $objData -> pwd;
$user = $objData -> name; //etc

Example Server Code: JAVA Servlet

JSONObject jObj = new JSONObject(request.getParameter("mydata")); // this parses the json
Iterator it = jObj.keys(); //gets all the keys

while(it.hasNext())
{
    String key = it.next(); // get key
    Object o = jObj.get(key); // get value
    //do something with it here
    //you can also do:
    String user = jObj.get("user");
}
like image 64
Christian Stewart Avatar answered Oct 14 '22 08:10

Christian Stewart