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>
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");
}
Changing ng-submit to ng-click should do the trick.
Related
I'm building a web API and I want to consume it through an MVC view. The API controller is to insert the user data and the MVC controller is to create the view. I have been looking for information and this is what I have been able to do with that information.
So, the API controller, simply inserts the data to the database through an stored procedure, I've tested with Postman and works fine:
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
public IActionResult post(Models.Request.UserModel model)
{
using (Models.AdminOrchardContext db = new Models.AdminOrchardContext())
{
Models.UserModel oUsuar = new Models.UserModel();
Models.OrchardTable tOrchard = new Models.OrchardTable();
oUsuar.Name = model.Name;
oUsuar.Email = model.Email;
tOrchard.OrchardLocation = model.OrchardLocation;
var uName = new SqlParameter("#name", oUsuar.Name);
var uEmail = new SqlParameter("#email", oUsuar.Email);
var hOrchardLocation = new SqlParameter("#OrchardLocation", tOrchard.OrchardLocation);
var idUserReg = db.Usuarios.FromSqlRaw("Exec UserAndOrchardInsert #name, #email" +
"#OrchardLocation",
new[] { uName, uEmail, hOrchardLocation});
db.SaveChanges();
}
return Ok();
}
}
The MVC controller where the view is added, from here the API is used with the user data on the view:
[HttpPost]
public IActionResult post(Models.Request.User model)
{
HttpClient hc = new HttpClient();
hc.BaseAddress = new Uri("https://localhost:44325/api/User");
var addRecToDB = hc.PostAsJsonAsync<Models.Request.User>("User", model);
addRecToDB.Wait();
ViewBag.message = "Ok!";
return View();
}
And the view:
#model Huerbog.Models.Request.User
#{
ViewData["Title"] = "post";
}
<h1>User registration</h1>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<h4>Orchard-related field</h4>
<div class="form-group">
<label asp-for="OrchardLocation" class="control-label"></label>
<input asp-for="OrchardLocation" class="form-control" />
<span asp-validation-for="OrchardLocation" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
<h4>#ViewBag.message</h4>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Now, the problem is that when I open the view, even when the API is running, on the page appears the Error 405, I don't know what or where exactly is the error.
the problem is that when I open the view, even when the API is running, on the page appears the Error 405, I don't know what or where exactly is the error.
Please note that your action post contains the [HttpPost] attribute, which constrains matching to HTTP Post request(s) only.
While you enter URL to access https://xxx/controller_name/post from browser side, browser would help make HTTP Get request to server, which cause 405 Method Not Allowed error.
To fix it, you can try to add a HttpGet post method to make the endpoint support HTTP Get method request(s), like below.
[HttpGet]
public IActionResult post()
{
return View();
}
[HttpPost]
public IActionResult post(Models.Request.User model)
{
//...
i'm approching angularJS and i'd like to submit a form to db via php.
i tried this but it does not work.
any help?
i get an error when i click the submit button.
thanks.
//index.html
angular.module("myApp")
.controller("addUtentiCtrl", function($scope, $http) {
$scope.utenteForm = {};
$scope.submit = function() {
$http({
method : 'POST',
url : 'backInsertUtenti',
data : param($scope.utenteForm),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function() {
alert("Dati inseriti correttamente!");
})
.error(function() {
alert("Errore inserimento dati!");
});
};
});
//aggiungiUtente.html
<form ng-submit="submit()" ng-controller="addUtentiCtrl" novalidate>
<input type="text" ng-model="utenteForm.nome" name="nome" ng-maxlength="10" ng-required="true">
<input type="text" ng-model="utenteForm.cognome" name="cognome" ng-maxlength="10" ng-required="true">
<input type="text" ng-model="utenteForm.citta" name="citta" ng-maxlength="10" ng-required="true">
<input ng-enable="utenteForm.$valid" type="submit" id="submit" value="Submit" />
</form>
//backInsertUtenti.php
<?php
//define of variable for the connection
$db= new mysqli($host,$username,$password,$db_name);
$sql=$db->prepare("INSERT INTO utenti (id, nome, cognome, citta) VALUES (0, ?, ?, ?)");
$sql->bind_param('sss',$_POST['nome'],$_POST['cognome'],$_POST['citta']);
$sql->execute();
?>
I'm trying to send a post form to a PHP script, and every time, the POST request shows as canceled.
My controller looks like this:
var authenticationControllers = angular.module('authenticationControllers', []);
authenticationControllers.controller('Authentication', ['$scope', '$http', function($scope, $http) {
$scope.WPlogin = function () {
var mydata ={
'action': 'ajaxlogin',
'username': $scope.user.username,
'password': $scope.user.password,
'security-login': pluginParams.nonce,
'_wp_http_referer': '/s/play/'
};
$http({
method: 'POST',
url: $scope.ajaxURL, //This is defined earlier, I'm sure this is valid
data: jQuery.param(mydata),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
console.log(data.message);
}).error(function(e){alert('error')});
};
}]);
And the form looks like this:
<div class="white-popup mfp-hide" id="login-modal" ng-controller="Authentication">
<form name="loginform" id="loginform" novalidate>
<h1>Login</h1>
<p class="status"></p>
<label for="username">Username</label>
<input id="username" type="text" name="username" ng-model="user.username" ng-required="true">
<label for="password">Password</label>
<input id="password" type="password" name="password" ng-model="user.password" ng-required="true">
<a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>
<button class="submit_button" ng-disabled="loginform.$invalid" ng-click="WPlogin()" type="submit" name="submit"> Login</button>
</form>
</div>
Whenever I try to submit the form, the error alert pops up, but no console errors. Then, the page reloads, and I can see the form parameters in the URL (like a get request), and if I then submit my form (without deleting the get parameters), then the request is a success.
Can anyone tell me what I'm doing wrong?
Update
I added $event.preventDefault(); to the form (passing $event from the form), and now it all works as expected, but I don't understand, why do I need that? I thought AngularJS would automatically prevent the form submission.
I followed the following tutorial (https://code.tutsplus.com/tutorials/laravel-4-a-start-at-a-restful-api-updated--net-29785) to create a REST API with Laravel. Here we're creating a new Url which gets two inputs: a url and description and stores it to a database.
public function store()
{
$url = new Url;
$url->url = Request::get('url');
$url->description = Request::get('description');
$url->user_id = Auth::user()->id;
$url->save();
return Response::json(array(
'error' => false,
'urls' => $urls->toArray()),
200
);
}
In trying to teach myself AngularJS, I've been trying to connect this REST API with an AngularJS front end. Here's my form:
<form data-ng-controller="formController">
<p>Store a URL To Read Later:</p>
<div class="form-group">
<input class="form-control" type="text" placeholder="Enter URL here" data-ng- model="newurl" />
</div>
<p>Description:</p>
<div class="form-group">
<input class="form-control" type="text" placeholder="Enter a brief description" data-ng-model="newdescription" />
</div>
<div class="form-group text-right">
<button class="btn btn-success" data-ng-click="submitUrl()">Add To List</button>
</div>
</form>
The data-ng-click is calling the submitUrl function which I have defined in the FormController.
function formController($scope, $http) {
$scope.submitUrl = function() {
var data = { 'url': $scope.newurl, 'description': $scope.newdescription };
$http.post("http://readitlater.loc/api/v1/url/", data )
}
}
I guess I'm puzzled as to how to get the input data to the public function store() and what kind of data it's expecting. Thanks for your time.
I figured it out. Rewriting like this, solved the problem.
function formController($scope, $http) {
$scope.submitUrl = function() {
var data = { 'url': $scope.newurl, 'description': $scope.newdescription };
$http({
method: 'POST',
url: 'http://readitlater.loc/api/v1/url/',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
data: $.param(data)
});
AngularJS sends POST requests with application/json type & JSON body by default. I'm not familiar with Laravel, but looks like using Input instead of Request is what you need: http://laravel.com/docs/4.2/requests#basic-input
We are using Spring 4 (Annotation based configuration) and AngularJS for building our application. In one of the usecase, we need to upload a document. On submitting the form, we need to send the form data (apart from file uploaded file, there are fields which are part of the form) and the file content as part of the POST request.
#Bean(name="multipartResolver")
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
The HTML form contents:
<form method="post" id="fromFileUpload"
enctype="multipart/form-data" ng-submit="create()">
<div class="form-group">
<label for="inputValue" class="col-md-offset-2 col-md-4 form-element">Input Value</label>
<div class="col-md-6 form-element">
<input class="form-control" ng-model="model.value"
name="val" required autofocus>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4 col-xs-12" for="file">Please
upload the file : <span class="required">*</span>
</label>
<div class="col-xs-4 input-max controls ">
<input class="inline-block" type="file" name="file"
ng-model="file" data-rule-required="true" id="file"
accept=".xls">
</div>
<span id="vaildFile" class="text-success icon-ok hide">Valid
File</span> <span id="invaildFile" class="text-error icon-remove hide">
Invalid File</span>
</div>
<div class="box-header">
<div class="actions">
<button type="submit" class="btn btn-primary">
<i class="icon-arrow-right"></i> Create
</button>
</div>
</div>
</form>
Below is the angularJS code :
$scope.create = function() {
var formData=new FormData();
formData.append("file",$scope.file);
formData.append("docData", angular.toJson($scope.model));
console.log(formData);
$http({
method: 'POST',
url: "http://localhost:8080/saprof/value",
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headers) {
return data;
}
})
.success(function(data, status) {
alert("Success");
})
.error(function(data, status) {
alert("Error");
});
};
Below is the controller Code (Annotated with #RestController)
#RequestMapping(value="/saprof/value", method=RequestMethod.POST)
public void createValue(HttpServletRequest request, HttpServletResponse response, HttpSession session){
LOGGER.info("Request is of type MultiPartRequest "+(request instanceof MultipartHttpServletRequest)); // false
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
LOGGER.info("isMultiPart Request : "+isMultipart); // false
}
Problem:
I am getting RequestFacade object as the request object and not MultiPartServletRequest. Hence i am not able to retrieve the form data + file contents from this request.
When see the request which is been sent using browser, below is the content:
Request Payload
------WebKitFormBoundaryzfZtWVlK6xH8aSyf
Content-Disposition: form-data; name="file"
[object Object]
------WebKitFormBoundaryzfZtWVlK6xH8aSyf
Content-Disposition: form-data; name="docData"
{"value":"test"}
------WebKitFormBoundaryzfZtWVlK6xH8aSyf--
Need your help in correcting my mistakes. Let me know if you need any further details. Really appreciate your help.
Regards,
Manjunath
I used this module on my own project and it worked like a charm:
danialfarid/ng-file-upload