How to pass String Array from html input to Angular http Post? - java

I want to pass some text input as array string to angular controller. I'm able to send single input as POST param and get it in Serlvet by using String key = request.getParameter("key");
This is my form
<form ng-controller="FormController" ng-submit="submitForm()" class="ng-valid ng-scope ng-dirty ng-valid-parse">
<p>Text1: <input type="text" name="ancestor" ng-model="blob.ancestor" class="ng-valid ng-dirty ng-touched ng-empty"></p>
<p>Text2: <input type="text" name="ancestor" ng-model="blob.ancestor" class="ng-valid ng-dirty ng-valid-parse ng-empty ng-touched"></p>
<p><input type="submit" class="btn btn-primary" value="Confirm"></p>
</form>
and this is my js script:
var app = angular.module('myApp', []);
app.controller('FormController', FormController);
FormController.$inject = ['$scope', '$http', '$httpParamSerializerJQLike'];
function FormController($scope, $http, $httpParamSerializerJQLike) {
$scope.blob = {};
$scope.submitForm = function() {
alert(JSON.stringify($scope.blob));
$http({
method : 'POST',
url : '/javaAngularJS',
data: $httpParamSerializerJQLike($scope.blob),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
}
});
};
}
Again, i'm able to send single param but i want to send "ancestor" with multiple values and get it using String ancestors[] = reuest.getParameterValues("ancestor"); in my Post method on servlet.

Let us assume that from your backend you are getting value of ancestor as [1,2,3,4] as array . you can bind this value to input field with ng-repeat like this
In Controller:
$scope.blob = {};
$scope.blob.ancestor = [1, 2, 3, 4];
In HTML:
<form ng-submit="submitForm()" class="ng-valid ng-scope ng-dirty ng-valid-parse">
<p ng-repeat="ancestor in blob.ancestor">Text {{$index +1}}: <input type="text" name="ancestor" ng-model="ancestor" class="ng-valid ng-dirty ng-touched ng-empty"></p>
<p><input type="submit" class="btn btn-primary" value="Confirm"></p>
</form>
Now in submitForm() click we will perform this to send data to backend in array
$scope.submitForm = function() {
console.log($scope.blob); // result:{"ancestor":[1,2,3,4]}
$http({
url: 'http://localhost:8080',
method: "POST",
params: {
ancestor: $scope.blob.ancestor
}
}).success(function(data) {
console.log(data);
}).error(function(data) {
console.log(data);
});
}
The data will go in paramter and the url will look like this:
http://localhost:8080?ancestor=1&ancestor=2&ancestor=3&ancestor=4

Related

Bind Form Data as JSON String/String Array to Request Params In String

I have a form which I would like to send to my controller via ajax:
<div class="row">
<label for="username" class="col-sm-2 col-form-label my-auto">Username:</label>
<div class="col-sm-10 my-auto">
<input type="text" class="form-control" id="username" name="username">
</div>
</div>
<div class="row">
<label for="password" class="col-sm-2 col-form-label my-auto">Password:</label>
<div class="col-sm-10 my-auto">
<input type="text" class="form-control" id="password" name="password">
</div>
</div>
<div class="row" id="ratingRow">
<label for="adminFoci" class="col-sm-2 col-form-label my-auto">User Rating:</label>
<div class="col-sm-auto my-auto">
<select class="selectpicker" multiple data-live-search="true" name="adminFoci" id="adminFoci" title="Choose Foci">
<c:forEach items="${foci}" var="focus">
<option name="${focus.focusName}" value="">${focus.focusName}</option>
</c:forEach>
</select>
</div>
<div class="col-sm my-auto">
<input type="text" class="form-control" id="rating" name="rating">
</div>
<div class="col-sm-auto my-auto" id="ratingButtonRow">
<div class="btn btn-info btn-sm" id="adminAddGroup">Add Rating</div>
</div>
</div>
<div class="row">
<label for="adminUserGroups" class="col-sm-2 col-form-label my-auto">User's Groups:</label>
<div class="col-sm-auto my-auto">
<select class="selectpicker" multiple data-live-search="true" id="adminUserGroups" name="groups" title="Choose Groups">
<c:forEach items="${groups}" var="group">
<option name="${group.groupName}" value="${group.groupName}">${group.groupName}</option>
</c:forEach>
</select>
</div>
</div>
<div class="row">
<label class="col-sm-2 col-form-label my-auto">User's Roles:</label>
<div class="col-sm-10 my-auto">
<select class="selectpicker" multiple data-live-search="true" id="adminUserRoles" name="roles" title="Choose Roles">
<c:forEach items="${user.roles}" var="role">
<option name="${role.name}" value="${role.name}">${role.name}</option>
</c:forEach>
</select>
</div>
</div>
I catch the form submit and serialize the form data:
$("#modalForm").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: form.attr('action'),
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify($(this).serializeArray()),
success: function(data)
{
table.row('.selected').ajax.reload();
}
});
});
I then try to bind data of the json string array to request params in my controller:
#PostMapping(value="/AdminCreateUser", consumes = MediaType.APPLICATION_JSON_VALUE)
public void createUser(#RequestParam String username, #RequestParam String password, #RequestParam (required = false) String[] roles,
#RequestParam (required = false) String[] groups){
User user = new User(username, password);
if(roles != null){
Set<Role> roleList = roleService.findRoles(roles);
if(roleList.size() > 0){
user.setRoles(roleList);
}
}
if(groups != null){
Set<Group> groupList = groupService.findGroups(groups);
for(Group group: groupList){
group.addMember(user);
groupRepository.save(group);
}
}
userRepository.save(user);
}
However I get Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'username' is not present]. Does Jackson not bind matching elements of the json string array to the request parameters? If not, how do I do this? I want to save myself the effort of sending each form field as separate data
The output of serialize array will be,
[
{
"name" : "username",
"value" : "test"
},...
]
Then change the java code as,
public void createUser(#RequestBody String body){
Convert string to JSONObject and handle it as JSON. Then this will work.
If you want to handle with Request Param.
Change the content-type to multipart/form-data and post it directly to the API.
There are two way.
By using application/json
Modify your js code like this.
$("#modalForm").submit(function(e){
e.preventDefault();
var form = $(this);
//convert form data to json array of Object(name value pair)
data = []
var x = $(this).serializeArray();
$.each(x, function(i, field){
var name = field.name; var value = field.value;
data[i] = {name : value};
});
$.ajax({
type: "POST",
url: form.attr('action'),
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function(data)
{
table.row('.selected').ajax.reload();
}
});
});
Modify your controller
public void createUser(#RequestBody CreateUserDto createUserRequest){
If you want to use request param change content-type to multipart/form-data.

How to place returned JSON data in a HTML Form

I need to place returned JSON data in HTML Form. I called database using web services and get JSON data. What I want is to place these JSON data into HTML input fields.
Sample JSON data (Returned as an array)
[{"username":"demo","email":"demo#gmail.com","password":"123"}]
The code in List.jsp
<form>
Enter Username:<br>
<input type="text" id="usernameEn" name="username"><br>
<button id="btnGet">Get</button>
</form>
<br><br>
<form>
Username:<br>
<input type="text" id="username" name="username"><br>
Email:<br>
<input type="text" id="email" name="email"><br><br>
Password:<br>
<input type="text" id="password" name="password"><br><br>
</form>
<script type="text/javascript">
$(document).ready(function()
{
$("#btnGet").click(function(event)
{
event.preventDefault();
$.ajax({
type: 'GET',
url: "http://localhost:8080/WebServiceTest2/webresources/users/get/" + $('#usernameEn').val(),
dataType: "json",
success: function(data) {
console.log(data);
var userDetails = data;
renderDetails(userDetails);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus);
}
});
});
});
function renderDetails(data)
{
$('#username').val(data.username);
$('#email').val(data.email);
$('#password').val(data.password);
};
</script>
Your REST service is returning an array, so to populate the form you'd have to access the first element of the array:
$('#username').val(data[0].username);
$('#email').val(data[0].email);
$('#password').val(data[0].password);
Or you could do the assignment higher up so you don't have to change your renderDetails() function:
var userDetails = data[0];
Probably best to also add a check to see whether the returned array is not empty.

how to send json data to server using ajax

refer.jvmhost.net/refer247/registration, this is my url,i have to fetch request to this url like user details and should get the appropriate response in json format with status n error if it contains ..dont give me android code..
this is html page.
<head>
<script type="text/javascript" src="json2.js"></script>
</head>
<body>
<div data-role="page" data-theme="c">
<div data-role="header" data-position="fixed" data-inset="true" class="paddingRitLft" data-theme="c">
<div data-role="content" data-inset="true"> <img src="images/logo_hdpi.png"/>
</div>
</div>
<div data-role="content" data-theme="c">
<form name="form" method="post" onsubmit="return validate()">
<div class="logInner">
<div class="logM">Already have an account?</div>
<div class="grouped insert refb">
<div class="ref first">
<div class="input inputWrapper">
<input type="text" data-corners="false" class="inputrefer" placeholder="Userid" name="userid" id="userid" />
</div>
<div class="input inputWrapper">
<input type="password" data-corners="false" class="inputrefer" placeholder="Password" name="password" id="password" />
</div> <input type="submit" data-inline="true" value="Submit" onclick="json2()">
<p>Forgot Password
</p>
</div>
</div>
<div class="logM">New user? Create refer Account</div>
<input type="button" class="btnsgreen" value="Sign Up! its FREE" class="inputrefer" data-corners="false" data-theme="c" />
</form>
</div>
</div>
<p style="text-align: center;">© refer247 2013</p>
</div>
</body>
this is json2.js
function json2()
{
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
//var parsed = jsonString.evalJSON( true );
alert(json1["username"]);
alert(json1["password"]);
};
so tell me how to send the json data to that url n obtain some response like if email
id is already exist if u registering with that id ..then give some error
like email id already exist n if registerd succesfully then give respone like registerd successfully and status msg..200 okk...
You can use ajax to post json data to specified url/controller method. In the below sample I am posting an json object. You can also pass each parameter separately.
var objectData =
{
Username: document.getElementById('userid').value,
Password: document.getElementById('password').value
};
var objectDataString = JSON.stringify(objectData);
$.ajax({
type: "POST",
url: "your url with method that accpects the data",
dataType: "json",
data: {
o: objectDataString
},
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
And your method can have only one parameter of string type.
[HttpPost]
public JsonResult YourMethod(string o)
{
var saveObject = Newtonsoft.Json.JsonConvert.DeserializeObject<DestinationClass>(o);
}
$.ajax({
url: urlToProcess,
type: httpMethod,
dataType: 'json',
data:json1,
success: function (data, status) {
var fn = window[successCallback];
fn(data, callbackArgs);
},
error: function (xhr, desc, err) {
alert("error");
},
});
function addProductById(pId,pMqty){
$.getJSON("addtocart?pid=" + pId + "&minqty="+ pMqty +"&rand=" + Math.floor((Math.random()*100)+1), function(json) {
alert(json.msg);
});
}
Here is a simple example, which will call on button click or onclick event and call addtocart servlet and passes 2 argument with it i.e. pId and pMqty.
and after successful completion it return message in alert which is set in that servlet in json.
var json1={"username":document.getElementById('userid').value,
"password":document.getElementById('password').value,
};
$.ajax({
url: '/path/to/file.php',
type: 'POST',
dataType: 'text',//no need for setting this to JSON if you don't receive a json response.
data: {param1: json1},
})
.done(function(response) {
console.log("success");
alert(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
on the server you can receive you json and decode it like so:
$myjson=json_decode($_POST['param1']);

Getting Response Text From Ajax Call

I am trying to get the response from an Ajax call into a html label. I am using a tomcat server. Ia m able to see the description returned form the server however how do i get the responses into the lable text. Under is what i have tried:
Jquery
function GetDescription(Id){
$.ajax({
type:'GET',
url:'getDescription.htm',
data:{dId:Id},
dataType: 'json',
success: function (data) {
$('.TypeDesc').text = data.responseText;
}
});
}
$(document).ready(function() {
$(".photos").each(function(i){
if ($(this).val() != '') {
var image = new Image();
image.src = $(this).val();
image.onload = function(){
var typeId = document.getElementsByClassName("TypeId")[i].value;
GetDescription(typeId);
var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
ctx.drawImage(image,0,0, 320, 240);
}
}
});
});
html
</head>
<body>
<div id ="content">
<c:forEach items="${object}" var="i">
<div id="table">
<div>
<p><canvas class="canvas" height="240" width="320"></canvas>
</div>
Name:- ${i.fName} ${i.lName}
<input type="hidden" id="photo" value="${i.photo}" class="photos"/>
<input type="hidden" id="Number" value="${i.Number}" />
<input type="text" class="TypeId" value="${i.citizenTypeId}"/>
<label class="TypeDesc"></label>
</div>
</c:forEach>
</div>
</body>
</html>
The problem is that you're telling jQuery you're expecting JSON:
dataType: 'json',
...and so it's (trying to) parse the response as JSON and pass you an object, but then you're trying to use it like a raw XHR object.
If you want the text, remove the dataType or change it to dataType: 'text', and then use data which will be a string.
Your other problem is that text is a function, not a property, so you need to call it.
So:
dataType: 'text',
success: function (data) {
$('.TypeDesc').text(data);
}
Please add this to the parameters of the ajax call
success: function(data) {
$('.TypeDesc').each(function(){
$(this).text(data);
});
}
You need to give the lable a unique ID like id="TypeDesc{i}" or something different.
So you can refer to it something like this:
$('#TypeDesc{i}').text = data.responseText;

JQuery disable form and change div contents

Im using the following ajax code to submit data from a form to a servlet and then have the servlet send data back (havent quite mastered this part yet).
Side question, the variable id is obtained from the .jsp file by using
`<script> var id = '${id}' </script>`
Is there a better way to access this variable directly from inside a .js file that is loaded on the page ? It works as is but it seems messy.
$(document).ready(function () {
$('.doAction').click(function () {
var rel = parseInt($('.doAction:checked').attr('rel'));
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
data: {
rating: rel,
itemID: id
},
url: 'Ratings',
success: function (data) {
}
});
});
});
The HTML form code is
<div id=holder>
<div id="rating">
Rating
<form id="ratingsform" name="ratingsform">
<input class="doAction" type="radio" name="ra1" rel="1" />
<input class="doAction" type="radio" name="ra1" rel="2" />
<input class="doAction" type="radio" name="ra1" rel="3" />
<input class="doAction" type="radio" name="ra1" rel="4" />
<input class="doAction" type="radio" name="ra1" rel="5" />
</form>
</div>
</div>
So what i want to happen is when a radio button is selected, the form is disabled so that new radio buttons can't be pressed (so the servlet cant be spammed to death). When the servlet responds to the ajax post call, I would like to change the contents of the div "rating" to display the updated ratings and remove the ability to vote i.e remove the radio buttons / form. I have the server side code working except for figuring out how to return the values required which hopefully is pretty straight forward.
Any suggestions ?
well check my comments to understand the change
$(document).ready(function () {
var id = '${id}' // you can have it here
$('.doAction').click(function () {
var rel = $('.doAction:checked').attr('rel'); // you need not parse to int because it will always string in parameter
$('.doAction').prop('disabled', true); // to disable radio button
$.ajax({
type: 'POST',
dataType: 'html', // change this since your servlet response is html not json
cache: false,
data: {
rating: rel,
itemID: id
},
url: 'Ratings',
success: function (data) {
$('#rating').html(data); // assuming response as {"rating" : 4.4}
}
});
});
});
In your server-side scripting, you need to print the data you would like sent back, then call it through the success function of the $.ajax object:
// Other AJAX...
success:function(msg){
$('#rating').html(msg);
}
// Other AJAX
I'm not the most familier with JSP, however I believe the command is something like out.print().
// Your js
$(document).ready(function () {
$('.doAction').live('click',function () {
// If we click then it is checked
var rel = parseInt($(this).attr('rel'));
// The id of the input hidden
var id = $('#theID').val();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
data: {
rating: rel,
itemID: id
},
url: 'Ratings',
success: function (data) {
// Displays the data returned by your servlet
$('#rating').html(data);
}
});
});
});
// HTML
<div id=holder>
<div id="rating">
Rating
<form id="ratingsform" name="ratingsform">
<input type="hidden" name="theID" value='${id}'/>
<input class="doAction" type="radio" name="ra1" rel="1" />
<input class="doAction" type="radio" name="ra1" rel="2" />
<input class="doAction" type="radio" name="ra1" rel="3" />
<input class="doAction" type="radio" name="ra1" rel="4" />
<input class="doAction" type="radio" name="ra1" rel="5" />
</form>
</div>
</div>
First of all, the server returns data? How is this returned? I would to this:
...
success: function (data) {
$("#ratings").html('<div class="rating '+rel+'stars"></div>');
}
...
And create 2 classes, one called rating and 5 more called 1,2,3,4,5stars, that would work.
Good luck!

Categories