I am using Jquery form plugin to upload file in Ajax request.File is successfully sent to server but on response browser is asking to save response with following popup
Here is my HTML
<form:form name="newRequestForm" id="newRequestForm" modelAttribute="requestForm" method="POST">
<form:input path="mrnFile" type="file" size="40"/>
</form:form>
JS
// Initializing Jquery form
$(function() {
$('#newRequestForm').ajaxForm();
});
// This function is called on click event of submit button
function submitDataRequest(formAction) {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
url: formAction,
dataType: 'json'
};
$('#newRequestForm').ajaxSubmit(options);
}
function showRequest(formData, jqForm, options) {
alert('About to submit: ');
return true;
}
function showResponse(data, statusText, xhr, $form) {
Alert("In response..")
if (!data.actionPassed) {
showErrors(data.errors);
$("#hideOrShowErrors").show();
} else {
showConfirmation(data, confirmationMsg, formName, successFormAction);
}
}
showResponse
is never invoked instead browser shows the popup.
I checked through Firebug, the response code is 200
still success callback is not executed.
After reading some similar question I think it has something to do with server response type. So I did following in my spring controller
public ResponseEntity<ResponseDTO> save(@ModelAttribute("dataRequestForm") DataRequestFormDTO dataRequestFormDTO, BindingResult result, SessionStatus status, Model model, HttpServletResponse response) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<ResponseDTO>(responseDTO, responseHeaders, HttpStatus.CREATED);
}
On both side I have data type as json
but still I am getting the popup.Am I making any blunder?
Thanks!
EDIT:
Updated JS
function submitDataRequest(formAction) {
var options = {
beforeSubmit: function(){
alert("Before submit");
}, // pre-submit callback
success: function(){
alert("On success");
}, // post-submit callback
url: formAction
}
$('#newRequestForm').ajaxSubmit(options);
}
Still I get the same popup and success
callback is not fired.
Added initBinder
in controller
@InitBinder
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws ServletException {
binder.registerCustomEditor(CommonsMultipartFile.class,
new ByteArrayMultipartFileEditor());
}
After adding initBinder
I got following error
No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer
This is a common issue with IE and iframe (used by jquery form plugin to upload files with ajax).
I solved in two steps:
1) Server Side: remove headers, send back just the content.
2) Client-Side: do not set the ajax request dataType parameter and on success use the following code to extract json: