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:
Changing ng-submit
to ng-click
should do the trick.
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");
}