I'm trying to download a file through Ajax post request. But I'm not able to do this, I tried a lot but I am not getting. The bellow is the code, please guide me how to do this.
Query method
$(document).on({click: function() {
var elementId = $(this).attr('id').split("_");
var air = $('#itineraryAir_${formBean.tripDetailsId}').is(':checked');
var car = $('#itineraryCar_${formBean.tripDetailsId}').is(':checked');
var hotel = $('#itineraryHotel_${formBean.tripDetailsId}').is(':checked');
if(air == true || car == true || hotel == true){
$('#itinerary_modal').modal( 'hide');
$.ajax({
url: "<%=request.getContextPath()%>/viewBooking/downloadItinerary/" +air+"/"+car+"/"+hotel+"/"+elementId[2],
type: 'POST',
dataType: 'text/json',
beforeSend: function() {
},
success: function(data) {
},
complete: function() {
}
}, '.edit_hotel');
}else{
var result="Select itinerary."
showMsg($("#ItineraryMsg"),result,"alert-danger");
}
}
}, '.it_download');
In the above code, I'm getting Element-Id, air, car and hotel details and passing all these value through URL. In spring controller class dynamically I am generating PDF file and the file is generating, But I am not able to display for user to download it.
Server side code
//the below line of code to generate pdf file. It is generating pdf file but I am not able to pass to client.
public #ResponseBody void downloadInPDF(#PathVariable("air") Boolean air,
#PathVariable("car") Boolean car,
#PathVariable("hotel") Boolean hotel,
#PathVariable("tripDetailsId") String tripDetailsId,
HttpServletResponse response,HttpServletRequest request) throws IOException {
TripDetails td = tripDetailsService.get(Integer.parseInt(tripDetailsId));
Users user=userService.getByUserIdNew(String.valueOf(td.getUser().getUserId()));
Employee employee=employeeService.getEmployeeByEmployeeId(user.getEmployee().getEmployeeId());
if(hotel == true){
List<TripHotels> tripHotels = hotelService
.getHotelDetailsByTripId(td);
generatePdf.getPdfFileHotel(AppConstant.ETICKET_PATH, tripHotels, td,employee);
String filePathToBeServed = AppConstant.ETICKET_PATH + td.getTripId()
+ "_Hotel.pdf";
File fileToDownload = new File(filePathToBeServed);
InputStream inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename="+td.getTripId() + "_Hotel.pdf");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
}
}
Related
I have a webpage that is supposed to upload an image to the database with a name to describe the image. Think uploading a logo and the name of the companies logo.
When I select the image file and submit it uploads to the database and I can return that information to the webpage in a list. However, it is not encoded in the manner that I was expecting. I would like the image file to be uploaded as a blob so that I may convert the blob to Base64 and pass it to my web application.
This is what the blob code looks like if I manually upload the images using MySQLs gui.
"iVBORw0KGgoAAAANSUhEUgAACWAAAAnHCAYAAAAIV..." which I'm able to convert to Base64 later.
When I use my ajax web page to upload an image however, I receive
"QzpcZmFrZXBhdGhcU3ByaW5nLnBuZw==".
My question is, how can I have ajax upload it as a blob instead so that my Java application can properly call the blob and convert it to Base64?
ajax.js
$(function (){
var $skills = $('#skills');
var $logo = $('#logo');
var $techName = $('#techName');
$.ajax({
type: 'GET',
url: '/api/technologyList',
success: function(skills) {
$.each(skills, function(i, skill) {
$('#skills-list').append('<tr><td> ' + skill.logo + '</td>' + '<td>' + skill.techName + '</td></tr>')
})
}
})
$('#addSkill').on('click', function () {
var skill = {
techName: $techName.val(),
logo: $logo.val()
}
$.ajax({
type: 'POST',
url:'/api/technologyList',
data: skill,
contentType: "multipart/form-data",
processData: false,
success: function (newSkill) {
$('#skills-list').append('<tr><td> '+ newSkill.logo+ '</td>' +
'<td> '+ newSkill.techName + '</td></tr>')
console.log(skill)
}
})
})
})
addSkill.html
<table id="skills-list">
<tr>
<th>Logo</th>
<th>Technology</th>
</tr>
</table>
<form id="skillForm">
<input type="text" id="techName"/> <br>
<input type="file" enctype="multipart/form-data" id="logo"/>
<button id="addSkill">Add!</button>
</form>
HomeController
#GetMapping(value = "/technology")
public String technologyList(Model theModel) throws IOException {
try {
List<Skills> userSkillsList = skillsService.findSkillList("wmangram");
List<byte[]> logo = skillsService.findLogos();
List<String> base64List = new ArrayList<>();
boolean isBase64 = false;
for (int i = 0; i < logo.size(); i++) {
if (Base64.isBase64(logo.get(i))) {
String base64Encoded = new String((logo.get(i)), "UTF-8");
base64List.add(base64Encoded);
}
else {
byte[] encodeBase64 = Base64.encodeBase64(logo.get(i));
String base64Encoded = new String(encodeBase64, "UTF-8");
base64List.add(base64Encoded);
}
}
theModel.addAttribute("userSkills", userSkillsList);
theModel.addAttribute("userImages", base64List);
return "technology";
}
catch (NullPointerException nexc) {
return "nullexception";
}
}
You have to use a FormData object to upload multipart/form-data1 via ajax.
$('#addSkill').on('click', function () {
var skill = new FormData();
skill.append("techName", $techName.val());
skill.append("logo", $logo.prop("files")[0]);
$.ajax({
type: 'POST',
url:'/api/technologyList',
data: skill,
contentType: false, //don't set this, it will be set automatically and properly
processData: false,
success: function (newSkill) {
$('#skills-list').append('<tr><td> '+ newSkill.logo+ '</td>' +
'<td> '+ newSkill.techName + '</td></tr>')
console.log(skill)
}
})
})
Looking at the java code it doesn't look like it can handle a file upload, so this answer is only for the client side code.
This isn't strictly true but you wouldn't want to have to do it any other way.
The problem was that I wasn't handling the file in a manner that let the program read the files contents. Instead it was just receiving the fake file path with the file name.
Fixed by utilizing #RequestParam and MultipartFile then assigning to the object before passing to the DAO.
RESTController.java
#PostMapping("/technologyList")
public String uploadMultipartFile(#RequestParam("logo") MultipartFile file, #RequestParam("techName")String techName) {
User user = userService.findByUsername("wmangram");
try {
// save file to MySQL
Skills newSkill = new Skills(techName, file.getBytes(), user);
skillsService.createTechnology(newSkill);
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
return "FAIL! Maybe You had uploaded the file before or the file's size > 500KB";
}
}
i'm working on a project where i need to save PDF file when i click on a button ,
#RequestMapping(value = "/download/{filename}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> download(#PathVariable String filename) throws IOException{
String fullPath=FILE_PATH+""+filename+".pdf";
System.out.println(fullPath);
File file =new File(fullPath);
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentType(MediaType.APPLICATION_PDF);
respHeaders.add("Content-Disposition", "attachment; filename=" + filename);
respHeaders.add("Accept","application/pdf");
InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
return new ResponseEntity<InputStreamResource>(isr,respHeaders,HttpStatus.OK);
testing it with ARC it shows something like this
testing my rest
and for angular i have for my html
<button (click)="saveF(a)">Export</button></div>
my component.ts
a="a.pdf";
saveF(fileName){
this.authService.saveFile(fileName)
.subscribe(response=> {
this.saveToFileSystem(response)
},
err=>{
console.log(err);
console.log("not ok")
}
)
}
which call the function
private saveToFileSystem(response){
const contentDispositionHeader: string =response.headers.get('Content-Disposition');
const parts:string[]=contentDispositionHeader.split('.');
const filename=parts[1].split('=')[1];
const blob =new Blob([response._body]);
saveAs(blob,filename);
}
and finally my service
saveFile(fileName){if (this.jwtToken== null){
this.loadToken()}
return this.http.get('http://localhost:8080/download/'+fileName,{headers:new HttpHeaders({'Authorization':this.jwtToken})})}
}
and in my browser i get something like this but it doesnt download the file
enter image description here
#Daniomi ty for the answer , now it works , i had to add responseType , this is how i change it
saveF(fileName) {
this.authService.saveFile(fileName)
.subscribe(response => {
const name =fileName;
const blob = response;
saveAs(blob,name);
},
err => {
console.log(err);
console.log("not ok")
}
)
}
and in my service
saveFile(fileName) {
if (this.jwtToken == null) {
this.loadToken()
}
// const options = new RequestOptions({responseType: ResponseContentType.Blob });
return this.http.get('http://localhost:8080/download/' + fileName, {
headers: new HttpHeaders({'Authorization': this.jwtToken}), responseType: 'blob'
})
}
Hi I want to stream videos in client app but videos are located in server app. I am using java Restlet and Jquery Ajax to connect client app to server app. Through Ajax call i am connecting to Restlet. I don't know how to send response to ajax after streaming video from server side, how ajax receives response and how to play video in browser. Can any one help me to handle this.
Here is my code
Html:
<button id="playVideo" class="btn-primary">PlayVideo</button>
<video id="videoTab" height="300" width="500" style="display: none" controls ></video>
Ajax Call to server
$('#playVideo').click(function (){
var jsonObj = {};
jsonObj.userId = "siva";
jsonObj.file = "sample.mp4";
//console.log("json obje :"+ JSON.stringify(jsonObj))
// Rest call to play videos.
$.ajax({
type : 'GET',
url : config.streamVideo,
//dataType : 'json',
data : JSON.stringify(jsonObj),
contentType : "application/json",
mimeType : "video/mp4",
processData : false,
crossDomain : true,
success : function(result) {
//console.log("login result : " + JSON.stringify(result));
if (result) {
console.log("success.....");
srcPath = "data:video/mp4;"+result;
$('#videoTab').attr('src', srcPath);
$('#videoTab').css('display', 'block');
$('#videoTab').attr('autoplay', true);
} else {
alert('failed...');
}
},
error : function(){
alert('error')
}
});
});
RestletCode:
#Get
public InputRepresentation handleRequest(Representation entity) throws IOException, ResourceException {
// Set response headers
Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null) {
responseHeaders = new Series<Header>(Header.class);
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
logger.debug("+++++++++++++++++++Entered in play video restlet +++++++++++++++");
// Convert Rest type request to Servlet request
httpServletRequest = ServletUtils.getRequest(getRequest());
// Get Servlet context object.
sc = httpServletRequest.getServletContext();
// Get input file path.
logger.debug("------->getRealPath " + sc.getRealPath("/"));
String filePath = sc.getRealPath("/") + "WEB-INF\\data\\videos\\sample.mp4";
final File file = new File(filePath);
if (file.exists()) {
logger.debug("Requested file path : " + file.getAbsolutePath());
logger.debug("inputRepresentation :" + inputRepresentation);
fis = new FileInputStream(file);
inputRepresentation = new InputRepresentation(new InputStream() {
private boolean waited = false;
#Override
public int read() throws IOException {
waited = false;
// read the next byte of the FileInputStream, when reaching the
// end of the file, wait for 2 seconds and try again, in case
// the file was not completely created yet
while (true) {
byte[] b = new byte[1];
if (fis.read(b, 0, 1) > 0) {
return b[0] + 256;
} else {
if (waited) {
return -1;
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
logger.error("Exception while streaming video : ", ex);
}
waited = true;
}
}
}
}
}, MediaType.VIDEO_MP4);
} else {
logger.debug("Requested file not found : " + filePath);
}
//logger.debug("inputRepresentation :");
return inputRepresentation;
}
Thanks in advance
After reading your comment, here is my understanding of what you should do.
I would not send json to a resource in order to get something, I would just send a simple GET request.
You need:
a resource that returns the file of a video according to its identifier. For the matter of illustration, let's say its url template is /videos/{videoid}
a web page that contains the links, and the empty video player
some javascript that set the "src" attribute video player with the url defined above: /videos/{videoid}. The way you compute the videoid is your own business.
Here is the server code:
the Restlet application, that defines the URI templates
#Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
// attaches the resource that represents a video, according to its identifier
router.attach("/videos/{videoid}", VideoServerResource.class);
// ... other instructions
return router;
}
the video server resource:
public class VideoServerResource extends ServerResource {
private File video;
#Override
protected void doInit() throws ResourceException {
String videoId = getAttribute("videoid");
// Compute path
String path = "/tmp/" + videoId + ".mp4";
video = new File(path);
// takes care of not found status responses.
setExisting(video.isFile());
}
#Get("mp4")
public File represent() {
return video;
}
}
Here is the client code. This is a sample Web page, with an empty video player. When clicking on the button, the video player is asked to play the http://example.com:9000/videos/testvideo video. In your case, the value testvideo is simply deduced from the link the user click on.
<!DOCTYPE html>
<html>
<head>
<script src="/static/jquery.js"></script>
<script>
$('#playVideo').click(function (){
srcPath = "http://127.0.0.1:9000/videos/testvideo";
$('#videoTab').attr('src', srcPath);
$('#videoTab').css('display', 'block');
$('#videoTab').attr('autoplay', true);
});
</script>
</head>
<body>
<button id="playVideo" class="btn-primary">PlayVideo</button>
<video id="videoTab" height="300" width="500" style="display: none" controls ></video>
</body>
</html>
I hope this will help you.
I am working on a j2ee application. In my application I have a drop-down list(or Select element). I want to populate this drop-down list with JSON data as a Ajax response.
Below is the code what I have:
Server side Code (json_source.java) which generates a JSON response. :
package demo.model;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.*;
/**
* Servlet implementation class json_source
*/
public class json_source extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
JsonArray data_json=new JsonArray();
Statement st_loginId=null;
ResultSet rs_loginId=null;
try
{
Connection con=null;
Class.forName("oracle.jdbc.OracleDriver");
/* Connection String for "OPERWH"(exadata) Database */
con=DriverManager.getConnection("jdbc:oracle:thin:*************","*****","*****");
con.setAutoCommit(true);
st_loginId=con.createStatement();
rs_loginId=st_loginId.executeQuery("select login_id \"LOGIN ID\" from user_access");
//System.out.println("entered in frame_login_code");
int login_val=0;
JsonObject json_response=new JsonObject();
while(rs_loginId.next())
{
login_val++;
JsonObject json=new JsonObject();
json.addProperty("value", "login"+login_val);
json.addProperty("text", rs_loginId.getString(1));
data_json.add(json);
}
System.out.println(data_json);
json_response.add("aaData", data_json);
response.setContentType("application/Json");
response.getWriter().write(json_response.toString());
System.out.println(json_response);
}
catch(Exception ex)
{
System.out.println("Exception occured during retrieval of Login_Id in ComboBox :"+ex);
ex.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
and the JSON data which successfully generated through above server side code :
{
"aaData": [{
"value": "login1",
"text": "kapils"
}, {
"value": "login2",
"text": "davidn"
}, {
"value": "login3",
"text": "alanp"
}]
}
and Below is my Client side code (source1.jsp) which generate ajax request:
(Using $.ajax() ) :
<script type="text/javascript">
$(document).ready(function()
{
$('#id_trial').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"/demo_trial_application/json_source",
dataType: "json",
success: function (data) {
$.each(data.aaData,function(i,data)
{
alert(data.value+":"+data.text);
var div_data="<option value="+data.value+">"+data.text+"</option>";
alert(div_data);
$(div_data).appendTo('#ch_user1');
});
}
});
});
});
</script>
<body>
<div id="div_source1">
<select id="ch_user1" >
<option value="select"></option>
</select>
</div>
<input type="button" id="id_trial" name="btn_trial" value="Trial Button..">
</body>
OR Using ($.getJSON()) :
$.getJSON("/demo_trial_application/json_source", function (data) {
$.each(data.aaData, function (i, data) {
var div_data = "<option value=" + data.value + ">" + data.text + "</option>";
alert(div_data);
$(div_data).appendTo('#ch_user1');
});
});
Now when I clicked on button (#id_trial), the server side code executes successfully and as a result JSON object created. but i am not getting that "JSON response" in callback function of Success parameter using jQuery's ajax call.
and apart from jQuery's ajax call I also tried with $.getJSON function to receive JSON response..but I didn't get JSON data.
So please tell me if there is any mistake in my code, and how to get JSON data using above code and populate drop-down list.
I want to populate my dropdownlist with JSON data using ajax response.
please help me to sort out this problem...its very urgent for my application.
try to change the jquery method variable, it might be causing the problem (i.e., you are using the data variable coming from the ajax callback PLUS are then trying to assign it to the item object in the jquery method - changed to obj):
$.ajax({
type: "GET",
url:"/demo_trial_application/json_source",
dataType: "json",
success: function (data) {
$.each(data.aaData,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#ch_user1');
});
}
});
});
I use "for"
var List;
jQuery.ajax({
url: "/demo_trial_application/json_source",
type: "POST",
dataType: "json",
async: false,
success: function (data) {
List = data.aaData
$('#ch_user1').empty();
$('#ch_user1').append('<option value="">All</option>');
for (i in List ) {
$('#ch_user1').append('<option value="' + List[i].value + '">' + List[i].text + '</option>');
}
}
});
Working with Laravel this is my solution:
$("#YOUR_DIV").on("change", function(){
var selected = $(this).val();
makeAjaxRequest(selected);
})
function makeAjaxRequest(opts){
$.ajax({
type: "GET",
url : '{{ action('YOUR_CONTROLLER#YOUR_FUNCTION') }}',
data: { opts: opts },
success: function(data) {
NEW_JS_FUNCTION(data);
}
});
}
function NEW_JS_FUNCTION(params) {
$('#YOUR_DIV').empty();
$('#YOUR_DIV').append('<option value="">ALL</option>');
params.forEach(function(entry){
$('#YOUR_DIV').append('<option value="' + entry.KEY+ '">' + entry.TEXT + '</option>');
});
}
It works. Hope this can help.
We can populate dropdown like below . it's very easy for you all i guess.
var options = $("#options");
$.getJSON("/Country/GetAll/", function(response) {
$.each(response, function() {
options.append($("<option />").val(this.Id).text(this.Name));
});
});
<div class="col-lg-4">
<%--<input type="text" class="form-control" id="txtGender" />--%>
<select class='form-control DropDown' id="txtGender"></select>
</div>
--------------------------------------------------------------------------------
$(document).ready(function () {
$.ajax({
type: "POST",
url: "AjaxCallGrid.asmx/GetDropDown",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('.DropDown').empty();
$('.DropDown').append("<option value='0'>---Select---</option>");
$.each(result.d, function (key, value) {
$('.DropDown').append($("<option></option>").val(value.iD).html(value.firstName));
});
}
});
});
-------------------------------------------------------------------------
[WebMethod]
public List<Students> GetDropDown()
{
DataTable dt = new DataTable();
List<Students> result = new List<Students>();
using (SqlConnection con = new SqlConnection(#"Data Source=DOS-PC\MARJI;Initial Catalog=examples;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select id,firstname from Students ", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
result.Add(new Students
{
iD = Convert.ToInt32(dt.Rows[i]["id"].ToString()),
firstName = dt.Rows[i]["firstname"].ToString()
}
);
}
}
return result;
}
}
The simplest way is to download this library https://github.com/JocaPC/jquery-view-engine/tree/master/src . This JQuery library directly loads JSON into dropdows and looks like a perfect match for your example. You just need to put the following code:
success: function (data) {
$('#ch_user1').view(data.aaData);
}
Take a look at this page https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown for more details.
Try as follows
<select id="xxx"></select>
success: function (response) {
for (var i = 0; i < response.length; i++) {
$("#xxx").append("<option value='" + response[i]["id"] + "'>" + response[i]["name"] + "</option>");
}
}
This is how you can do it:
$(".ddEvent").on('change', function(e){
const selectedEvent = $(this).val();
$("#ddExhibitor").empty();
$("#ddExhibitor").append("<option value='-1'>-- Choose Exhibitor --</option>");
$.ajax({
url: '/dashboard/get-exhibitors/'+selectedEvent,
type: 'GET',
success: function success(data) {
if(data.exhibitors.length > 0){
data.exhibitors.forEach(exhibitor => {
$("#ddExhibitor").append("<option value='" + exhibitor.id + "'>" + exhibitor.exhibitor_name + "</option>");
});
}
},
error: function error(err) {
alert(data.error);
}
});
});
I have a web application with HTML / jQuery which ic connected with AJAX / JSON to a backend system with Java EE / Spring MVC.
In the frontend, a Person can be created by fill in the form fields and then it is submitted and this jQuery code executed:
var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {
alert("Person with ID "+data.person.id+"' added successfully");
});
In the best case, the Person is created and I'll get a Person object and I can access the values with data.person.*.
Now I want to validate the data which is sent to the backend system and in a case of an error, I want to display in the first step an alert error message.
I did this in the backend system:
#RequestMapping(value="add/", method=RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> addPerson(#RequestBody Person p, HttpServletResponse response) {
Set<ConstraintViolation<Person>> failures = validator.validate(p);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
Person person = this.personService.addPerson(p);
return Collections.singletonMap("person", new SerialPerson(person.getId(), person.getName(), ...));
}
}
// internal helpers
private Map<String, String> validationMessages(Set<ConstraintViolation<Person>> failures) {
Map<String, String> failureMessages = new HashMap<String, String>();
for (ConstraintViolation<Person> failure : failures) {
failureMessages.put(failure.getPropertyPath().toString(), failure.getMessage());
System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage());
}
return failureMessages;
}
My Person object is annotated, and I get the System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage()); on the console, that for example, "name - must be between 1-30 chars"
But how can create an alert message in jQuery in the frontend system?
Thank you in advance for your help & Best Regards.
Update: Link to the Spring MVC AJAX example, where I found the validationMessages method. But there is also no solution how to get the error message.
SOLUTION:
I have to call:
jQuery.ajax({
'type': 'POST',
'url': "add/",
'contentType': 'application/json',
'data': JSON.stringify(person),
'dataType': 'json',
'success': function(data) {alert("success");},
'error': function(xhr) {alert(xhr.responseText);}
});
You can do something like this:
var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {
if(data.person) {
alert("Person with ID "+data.person.id+"' added successfully");
}
else {
var errors = "";
for(var key in data) if(data.hasOwnProperty(key)) {
errors += data[key] + "\n";
}
alert(errors);
}
});
You shouldn't need to send back a bad request either. Is this what you want?
UPDATE
You can use the code shown in Spring Source, but you'd have to use jQuery.ajax
jQuery.ajax({
type: 'POST',
url: "add/",
data: person,
dataType: "json",
success: function(data) {
alert("Person with ID "+data.person.id+"' added successfully");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var errorJSON = JSON.parse(XMLHttpRequest.responseText); //if this is JSON otherwise just alerting XMLHttpRequest.responseText will do
var errors = "";
for(var key in errorJSON) if(errorJSON.hasOwnProperty(key)) {
errors += errorJSON[key] + "\n";
}
alert(errors);
}
});