Below is my code attempt to post an Json serialize object (java pojo having list of other pojos) with JQuery Ajax call to Spring MVC controller.
Getting Bad request error from server.
When the modalForm data is removed from the Json object the MainPojo data received correctly at server side.
Html Code
Fisrt form
-------------
<form id="mainForm">
.....
</form>
Form in the modal
-----------------
<form id="modelform" ..>
<div id="row">
<input type="text" id="subject" />
<input type="text" id="max" />
<input type="text" id="min" />
</div>
<div id="row">
<input type="text" id="subject" />
<input type="text" id="max" />
<input type="text" id="min" />
</div>
.............
</form>}
Jquery
var mainObject = $('#mainForm').serializeObject();
var modelObject = $('#modelform').serializeObject();
mainObject.marks = modelObject;
Json ( Expected)
{
"name": "Some Name",
"age": "10",
"marks": [
{
"subject": "maths",
"max": "20",
"min":"12"
},
{
"subject": "english",
"max": "20",
"min":"12",
}
]
}
Json (actual output with the above code)
{
"name": "Some Name",
"age": "10",
"marks": [
{
"subject": "maths",
"subject": "english"
},
{
"max": "20",
"max":"20",
},
{
"min": "12",
"min":"12"
}
]
}
//Ajax call
$.ajax({
url: '/save',
type: 'POST',
contentType: 'application/json',
mimeType: 'application/json',
data : JSON.stringify(mainObject),
dataType: 'json',
success: function(data) {
alert(data.msg);
},
error:function (xhr, ajaxOptions, thrownError) {
alert('Technical error occured');
}
});
Java Pojo's
public class MainPojo {
private String name;
private String age;
private Lists<marks>
..................
}
public class ModelPojo {
private String subject;
private String maxMarks;
private String minMarks;
.....................
}
Controller Method
#RequestMapping(value = "save", headers = "Accept=application/json",
method = RequestMethod.POST)
public #ResponseBody String save(#RequestBody final MainPojo mainPojo) {
}
Please help me to identify the problem.
Thank You.
Modify html text like this
<form id="mainForm">
<input name="name" type="text" value="Some Name">
<input name="age" type="text" value="20">
</form>
<form class="modelform">
<input type="text" value="subject" name="subject"/>
<input type="text" value="max" name="max"/>
<input type="text" value="min" name="min"/>
</form>
<form class="modelform">
<input type="text" value="subject" name="subject" />
<input type="text" value="max" name="max"/>
<input type="text" value="min" name="min"/>
</form>
Then write javascript code to assign object value
<script>
var mainObject = $('#mainForm').serializeObject();
var modelObject = [];
$('.modelform').each(function(o){
modelObject.push($(this).serializeObject());
})
mainObject.marks = modelObject;
</script>
i have
#RequestMapping(value = "/save", method = RequestMethod.POST)
public #ResponseBody
MyEvent saveOrganization(#RequestBody Organization organization) {
return new MyEvent('save',organization);
}
y your mvc-servlets.xml
<context:component-scan base-package="com.jrey.project.controllers" />
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
my jquery post
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [ o[this.name] ];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
<script>
$(document)
.ready(
function() {
$('.submit', '#form')
.click(
function() {
var data = JSON
.stringify($('#form')
.serializeObject());
console.log(data);
$
.ajax({
type : "POST",
url : '${pageContext.request.contextPath}/controller/organization',
data : data,
dataType : 'json',
contentType : 'application/json;charset=UTF-8',
success : function(data) {
$(
'<div>'
+ data.message
+ '</div>')
.dialog(
{
title : 'Organizacion',
modal : true,
buttons : {
'Aceptar' : function() {
document.location.href = data.location;
}
}
}
);
},
});
});
});
Related
I'm trying to delete multiple Items with the same name in my web app. But it's giving me an error 500 when I do the POST.
This is my Form Code
<form method="POST" name="deleteFormAdd" id="deleteFormAdd" enctype="multipart/form-data">
<input type="hidden" name="_csrf" th:value="${_csrf.token}" />
<!--Asset ID set to hidden so the User can't see it-->
<input type="hidden" th:each="deleteCategory, itemStat : ${DeleteCategoryObject}"
th:name="assetID"
th:value="${deleteCategory.assetID}"/>
<!-- For showing all the Asset to be deleted -->
<input class="w3-input w3-border w3-round-large" type="text"
th:each="deleteCategory, itemStat : ${DeleteCategoryObject}"
th:name="${DeleteCategoryObject[__${itemStat.index}__].assetType}"
th:value="${deleteCategory.assetType}"
disabled="disabled"/>
<br></br>
<input type="button" class="btn btn-primary btn-block" value="Yes" th:onclick="'javascript:submitForm(\'deleteFormAdd\',\''+#{/delete-asset}+'\')'" />
<button type="reset" onclick="window.location.href = 'manage-assets.html';" class="btn btn-default btn-block"> Cancel</button>
</form>
Submit Form Ajax
function submitForm(formID, url){
var formData = new FormData($("#" + formID)[0]);
$.ajax({
dataType: 'json',
url: url,
data : formData,
type : "POST",
enctype : "multipart/form-data" ,
processData : false,
contentType : false,
success : function(data) {
if (data.status == 1) {
openAlertDialog("Success", "The Asset type has been deleted!", "Continue", "manage-assets");
} else {
openAlertDialog("Error", data.message, "Continue", "manage-assets");
}
},
error : function(data) {
openAlertDialog("Error", data.message, "Continue", "manage-assets");
},
});
}
Spring Controller
#RequestMapping(value = "/delete-asset", method = RequestMethod.POST)
public #ResponseBody String deleteAsset(#ModelAttribute List<AssetCategory> assetCategories) {
JsonObject result = new JsonObject();
if (assetCategories != null && !assetCategories.isEmpty()) {
String[] arr = new String[assetCategories.size()];
for (int i =0; i < assetCategories.size(); i++) {
arr[i] = assetCategories.get(i).getAssetID();
}
assetService.deleteAssets(arr);
result.addProperty("result", "Success");
result.addProperty("status", 1);
result.addProperty("message", "Asset Deleted!");
}
return result.toString();
}
Spring Service
#Override
public AssetCategory deleteAssets(String[] assetID) {
return dao.deleteAssets(assetID);
}
Spring DAO
#Query("Delete From AssetCategory A WHERE A.assetID IN (:assetID)")
public AssetCategory deleteAssets(#Param("assetID") String[] assetID);
Spring Console Error
Failed to instantiate [java.util.List]: Specified class is an interface] with root cause
org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Specified class is an interface
This is the Form Data (it contains the asset ID's)
Seems issue with your ajax function. Check with below:
function submitForm(formID, url) {
var assetIdList = [];
var assetIdObj;
$("#" + formID).find('input[name="assetID"]').each(function () {
assetIdObj = {};
assetIdObj.assetID = $(this).val();
assetIdList.push(assetIdObj);
});
$.ajax({
dataType: 'json',
url: url,
data: {assetCategories: assetIdList},
type: "POST",
enctype: "multipart/form-data",
processData: false,
contentType: false,
success: function (data) {
if (data.status === 1) {
openAlertDialog("Success", "The Asset type has been deleted!", "Continue", "manage-assets");
} else {
openAlertDialog("Error", data.message, "Continue", "manage-assets");
}
},
error: function (data) {
openAlertDialog("Error", data.message, "Continue", "manage-assets");
},
});
}
Update this html code from:
<input type="hidden" th:each="deleteCategory, itemStat : ${DeleteCategoryObject}"
th:name="assetID"
th:value="${deleteCategory.assetID}"/>
To this:
<input type="hidden" th:each="deleteCategory, itemStat : ${DeleteCategoryObject}"
name="assetID"
th:value="${deleteCategory.assetID}"/>
You are using multipart/form-data. So, your request header has multipart/form-data Content-Type which have data as form type. like key=value.
So just remove #ModelAttribute annotation and add consumes properties to your mapping annotation.
//if you're using spring version more than 4.3, use below #PostMapping for readability
//#PostMapping(value = "/delete-asset", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
#RequestMapping(value = "/delete-asset", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public #ResponseBody String deleteAsset(List<AssetCategory> assetCategories) {
JsonObject result = new JsonObject();
//you can use apache's commons-collection
if (CollectionUtils.isNotEmpty(assetCategories)) {
//and you can also use stream api
String[] arr = assetCategories.stream()
.map(AssetCategory::getAssetID)
.toArray();
assetService.deleteAssets(arr);
result.addProperty("result", "Success");
result.addProperty("status", 1);
result.addProperty("message", "Asset Deleted!");
}
return result.toString();
}
I have this form
<div class="row">
<h1 class="page-header">
Create
</h1>
<form ng-submit="create()", enctype="multipart/form-data">
<div class="form-group">
<label>Name:</label>
<input type="text" ng-model="subforum.name" class="form-control" />
</div>
<div class="form-group">
<label>Desc:</label>
<input type="text" ng-model="subforum.desc" class="form-control" />
</div>
<input type="file" ngf-select ng-model="subforum.icon" name="subforum.icon"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFile">
<img ng-show="myForm.file.$valid" ngf-thumbnail="subforum.icon" class="thumb"> <button ng-click="subforum.icon= null" ng-show="subforum.icon">Remove</button>
<button class="btn btn-success" type="submit">Create</button>
</form>
``
In my JS
.config(function($stateProvider) {
$stateProvider.state('create', {
url:'/subforum/create',
views: {
'main': {
templateUrl:'subforum/create.tpl.html',
controller: 'CreateCtrl'
}
},
data : { pageTitle : "Create Subforum" }
})
and
.factory('subforumService', function($resource) {
var service = {};
service.create = function (subforum, success, failure) {
var SubForum= $resource ("/web-prog/rest/subforums");
SubForum.save({}, subforum, success, failure) ;
};
.controller("CreateCtrl", function($scope, $state, subforumService) {
$scope.create = function() {
$scope.subforum.author = JSON.parse(localStorage.getItem ("logedUser"));
subforumService.create($scope.subforum,
function(returnedData) {
$state.go("home");
},
function() {
alert("Error creating");
});
};
I know thats not best practice to save user in LocalStorage but for now its like that.
On backend i have controller and in that controller i have methode:
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<SubForumResource> createPodforum(#RequestBody SubForumResource sentPodforum) {
}
and SubForumResource is
public class PodforumResource extends ResourceSupport {
private String name;
private String desc;
private byte[] icon;}
with geters and seters and everything i need.
So when i have form without image it works without problems. But i need icon too. Im new to angularjs but need it for this project. When i try to use FormData() i dont know how to use $resource. So if someone can help me i would be thankful. This is my first prject i need to work front end so im lost.
You can refer below code for angularjs :
this.addEmployee = function (requestData, file) {
var data = new FormData();
data.append('file', file[0]);
data.append('requestData', new Blob([JSON.stringify(requestData)], {
type: "application/json"
}));
var config = {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
}
var url = "http://localhost:8080/addEmployee";
var promise1 = $http.post(url, data, config);
var promise2 = promise1.then(function (response) {
return response.data;
},
function errorCallback(response) {
alert(response.data.errorMessage);
});
return promise2;
}
And for controller :
#RequestMapping(value = "/addEmployee", method = RequestMethod.POST, consumes = {"multipart/form-data" })
#CrossOrigin
public CustomResponse addEmployee(#RequestPart("file") MultipartFile file, #RequestPart("requestData") Employee emp) {
}
Hi I'm trying to upload a image file to the server.I have used jCrop to crop the image before uploading and used canvas to get the cropped image coordinates.I have included controller and jsp files .But I'm not able to send formdata using ajax.
AppController.java
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("file") MultipartFile file, ModelMap model) throws IOException{
if (!file.isEmpty()) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
File destination = new File("/home/me/Desktop/"+name+".png");
model.addAttribute("username", name);
// something like C:/Users/tom/Documents/nameBasedOnSomeId.png
ImageIO.write(src, "png", destination);
//Save the id you have used to create the file name in the DB. You can retrieve the image in future with the ID.
}else {
System.out.println("file is empty");
}
return "prefs";
}
prefs.jsp
<script type="text/javascript">
$(function(){
$('.majorpoints').click(function(){
$(this).find('.hiders').slideToggle();
});
$("#imgInp").change(function(){
var c = $('.cropArea').Jcrop({
onSelect: updateCoords,
bgOpacity: .4,
setSelect: [ 100, 100, 50, 50 ],
aspectRatio: 16 / 9
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
readURL(this);
});
$('#btnCrop').click(function () {
var x1 = $('#x').val();
var y1 = $('#y').val();
var width = $('#w').val();
var height = $('#h').val();
var canvas = $("#canvas")[0];
alert(x1+""+y1+""+""+width+""+height);
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.height = height;
canvas.width = width;
context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
$("#imgInp").val(canvas.toDataURL("image/jpeg"));
};
var data = new FormData();
data.append('file', dataURItoBlob(canvas.toDataURL("image/jpeg")));
$.ajax({
url: 'upload',
data: data,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
img.src = $('#blah').attr('src');
});
});
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
function updateCoords(c)
{
console.log(c);
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
$('#btnCrop').show();
};
</script>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<form method="POST" action="upload" enctype="multipart/form-data">
Please select a file to upload :
<input type="file" name="file" class="file" id="imgInp" />
<div class="cropArea">
<img id="blah" src="#" alt="your image" />
</div>
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<canvas id="canvas" height="5" width="5"></canvas>
</form>
<input type="button" id="btnCrop" value="Crop" style="display: none" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
You are missing this param
enctype: 'multipart/form-data'
$.ajax({
url: 'upload',
data: data,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
type: 'POST',
success: function(data){
alert(data);
}
});
You should have this
var data = new FormData();
data.append('file', jQuery('#imgInp')[0].files[0]);
instead of
jQuery.each(jQuery('#imgInp')[0].files, function(i,file) {
data.append('file-'+i, file);
});
Later Edit 2:
in your function dataURItoBlob(dataURI) add callback like this:
function dataURItoBlob(dataURI, callback) {
...
callback();
}
then in
$('#btnCrop').click(function () { ...
data.append('file', dataURItoBlob(canvas.toDataURL("image/jpeg", function(){
$.ajax({
url: 'upload',
data: data,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
})));
this way, you are sure that you make the ajax call after dataURItoBlob is executed.
I am new to Jquery and Struts.
I need to send the form data to Struts2 action class using Ajax function.
My HTML form element is set as :
<div class="input-append date" id="from_date">
<input type="text" id="processDate" name="processDate" />
<span class="add-on"><i class="icon-th"></i></span>
</div>
<div>
<input id="submit-date" type="button" class="btn btn-primary" value="Search" />
</div>
I am using the JQuery Script as :
$('#submit-date').click(function() {
var processDate = $('#processDate').val();
alert(processDate);
$.ajax({
type : "POST",
url : "launchapptest",
data : processDate,
dataType : "json",
success : function(result) {
alert("Success");
}
});
}
Struts.XML file is written as :
<action name="launchapptest" class="com.ge.wd.action.LaunchAppTestAction">
<result type="json">
</result>
</action>
I have given execute method in Action Class :
String processDate;
public String getProcessDate() {
return processDate;
}
public void setProcessDate(String processDate) {
this.processDate = processDate;
}
public String execute() throws Exception {
processDate=getProcessDate();
System.out.println("Process Date : "+processDate);
}
Please help me as how can I receive this for data in the action class.
Thanks for the help. But issue is resolved, I changed the code to :
HTML:
<div class="input-append date" id="from_date">
<input type="text" id="processDateForm" name="processDate"/>
<span class="add-on"><i class="icon-th"></i></span>
</div>
<div>
<input id="submit-date" type="button" class="btn btn-primary" value="Search" />
</div>
Jquery :
$('#submit-date').click(function() {
var processDate = $('#processDateForm').val();
alert(processDate);
$.ajax({
/* type : "POST", */
url : "launchapptest",
/* contentType: "application/json; charset=utf-8", */
data : "processDateInput="+processDate,
dataType : "json",
async: true,
success : function(result) {
alert("Success");
}
});
and JAVA code :
public class LaunchAppTestAction extends ActionSupport {
private static final long serialVersionUID = -367986889632883043L;
//private ProcessDate pd = new ProcessDate();
private String processDateInput=null;
public String getProcessDateInput() {
return processDateInput;
}
public void setProcessDateInput(String processDateInput) {
this.processDateInput = processDateInput;
}
public String execute() throws Exception {
System.out.println("Process Date : "+processDateInput);
return SUCCESS;
}}
Struts.xml
<action name="launchapptest" class="com.ge.wd.action.LaunchAppTestAction">
<result name= "success" type="json">
</result>
</action>
I hope this works for anyone facing the same issue :)
Thanks again
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']);