Spring Ajax file upload - ajax

I am using jquery ajaxSubmit function for submitting my form. I also have file upload field in the form.
Here's the code of ajaxSubmit function.
$('#wizard-p-7').submit(function(e) {
$(".validationMessage").hide();
e.preventDefault();
var formURL = $(this).attr("action");
$(this).ajaxSubmit({
url : formURL,
async : false,
contentType: 'multipart/form-data',
success : function(data) {
if (data == "version match.") {
check = true;
} else {
check = false;
}
},
error : function(jqXHR,
textStatus,
errorThrown) {
alert("error:"+errorThrown);
window.location = "<%=application.getContextPath()%>/pages/error/globalError.jsp";
}
});
e.preventDefault(); //STOP default action
// e.unbind(); //unbind. to stop multiple form submit.
return false;
});
Here is my controller method
#RequestMapping(value = "/sectioneight", method = RequestMethod.POST)
public #ResponseBody Object sectioneight(#ModelAttribute("iepDTO") ProjectDTO iepDTO,
#RequestParam("id") String id) {
try {
List<MultipartFile> files = iepDTO.getPolicyBriefFiles();
if(files!=null){
for(MultipartFile file : files){
String filePath = "C:/temp/" + file.getOriginalFilename();
File dest = new File(filePath);
file.transferTo(dest);
}
}
}
catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
logger.error("ProjectController - sectioneight : "+ e.getMessage());
}
return "redirect:home";
}
Now the problem is if I select a file for uploading and submit the form everything works fine. But if I submit the form without selecting file it gives 400 Bad request error in the browser console. Can't find what is wrong.
Any clue?

Solved. Problem was because of ajax. If I don't select a file it sends null string in place of file.
The solution is now I check before submitting the form if file is selected or not. If not, I disable the field with jquery
if($("#policyBriefFiles").val()==""){
$("#policyBriefFiles").prop('disabled', true);
}
Life's good:)

Related

redirect to another jsp page

I m trying to redirect control to next jsp page. If the boolean value is true redirect to success jsp page else redirect to login page.
#RequestMapping(value = "/validate", method = RequestMethod.POST)
#ResponseBody
public ModelAndView(HttpServletRequest request, HttpServletResponse response, Model model) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
boolean validuser=employeeService.checkLogin(userName,password);
if(validuser == true)
{
model.setViewName("success");
return model;
}
model.setViewName("login");
return model;
}
This is my Ajax call.
$(document).ready(function() {
$("form").submit(function() {
var userName=$("#inputEmail").val();
var password=$("#inputPassword").val();
$.ajax({
type : "post",
url : "${pageContext.request.contextPath}/validate",
data : {userName:userName, password:password},
success:function(data){
alert(data);
},
error:function()
{
alert("Error ");
}
});
});
});
Control is not going to success block. Only the error alert is getting displayed.
public String validate(HttpServletRequest request, HttpServletResponse response, Model model) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
boolean validuser=employeeService.checkLogin(userName,password);
if(validuser == true)
{
return "redirect:/success";
}
else{
return "redirect:/login";
}
}
I have tried it using this approach. Still its entering error block.
Add window.location.href = 'YOUR_REDIRECT_URL' in your success callback.
success:function(data){
alert(data);
window.location.href = 'YOUR_REDIRECT_URL'; // redirect
},
If it's an ajax call, you can't use the redirect: in the return url. On your controller, return "http://example.domain.com/success". Then in your success handler use window.location.href = 'redirect_url'

MVC Controller getting 404 error

I have an MVC controller that has several Methods on it. One to show the View, 6 that are for jquery ajax methods. The View shows up correctly and here is the simple code
public ActionResult Queues()
{
return View();
}
On that view there are 2 datatable.net grids. That grid gets populated with a ajax call to this
[HttpGet]
public async Task<JsonResult> QueueOne()
{
try
{
....
var results = await GetData(queryString, authUser.AccessToken).ConfigureAwait(false);
var jsonObj = JsonConvert.DeserializeObject<DataTableWrapper<QueueItemForRead>>(results);
return Json(jsonObj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.Error(ex.Message, ex);
}
return Json("Error occured please try again");
}
which populates the grid correctly.
I have other functions on the page that call another endpoint on the page
public async Task<JsonResult> ItemComplete(Guid QueueId, long version)
{
try
{
...
var results =
await
PutData(queryString, JsonConvert.SerializeObject(itemCompleted), authUser.AccessToken)
.ConfigureAwait(false);
var jsonObj = JsonConvert.DeserializeObject<NewItemCommandResult>(results);
return Json(jsonObj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.Error(ex.Message, ex);
}
return Json("Error occured please try again");
}
and here is the JS that calls the above endpoint
$.ajax({
url: 'http://localhost:18171/Clients/CurrentActivity/ItemComplete' + "?QueueId=" + data + "&version=" + version,
type: 'PUT',
//contentType: 'application/json',
//dataType: 'json',
success: function (result) {
if (result.Result === 2) {
showSuccessNotification(name +
" has been Delivered to table.",
"Food Delivered");
}
//else {
//}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
console.log(XMLHttpRequest.status + ' ' +
XMLHttpRequest.statusText);
$(buttonName).hide();
},
beforeSend: function () {
// Code to display spinner
$(buttonName).hide();
$(completedAjax).show();
},
complete: function () {
// Code to hide spinner.
$(completedAjax).hide();
}
});
but everytime this function is run all I get a 404 error.
Sorry it was bad cut and paste job, the URL actually has signle quotes around it. and i get the base Url this way
var QueueUrl = '#Url.Action("QueueOne","CurrentActivity")';
so when it renders the actual url is '/Clients/CurrentActivity/QueueOne'
your url doesn't contain " " Or ' ' so it isn't considered as string it should be like
url: "/Clients/CurrentActivity/ItemComplete?QueueId=" + data + "&version=" + version,
Don't Use Your Local Domain IN the Url This Will Cause Problem In production Version if you forget to change it
you can also use Url Helper To Make valid Url Like
url: "#Url.Action("ItemComplete","CurrentActivity",new{area='Clients'})"+"'QueueId=' + data + "&version=" + version,

MVC3 ajax action request: handling answer

I'm doing an Ajax request to an MVC3 action and I want to process the JsonResult in the success or error function.
Currently the behaviour is strange: Before hitting my breakpoint in the action it hits the error function.
Can anyone help me please and has a hint?
My view:
<form id="myForm">
//fields go here...
<button id="myButton" onclick="myFunction();">ButtonName</button>
</form>
The ajax call:
function myFunction() {
if ($('#myForm').valid() == false) {
return;
}
var data = {
val1: $("#val1").val(),
val2: $("#val2").val()
};
var url = "/Controller/Action";
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: data,
success: function (data, statusCode, xhr) {
alert('1');
if (data && data.Message) {
alert(data.Message);
alert('2');
}
alert('3');
},
error: function (xhr, errorType, exception) {
alert('4');
var errorMessage = exception || xhr.statusText;
alert("There was an error: " + errorMessage);
}
});
return false;
}
My action:
[HttpPost]
public ActionResult Action(Class objectName)
{
var response = new AjaxResponseViewModel();
try
{
var success = DoSomething(objectName);
if (success)
{
response.Success = true;
response.Message = "Successful!";
}
else
{
response.Message = "Error!";
}
}
catch (Exception exception)
{
response.Success = false;
response.Message = exception.Message;
}
return Json(response);
}
If you look in the ajax call I get directly the alert #4 and only then the action gets called which is too late. Unfortunately the exception is null. Directly after that the view gets closed.
You are not preventing the default onclick behavior. Can you try the following instead?
onclick="return myFunction()"

not able to navigate using RedirectToAction

I am notable to naviagate to another page using Redirect ie when result is false, then i would like to navigate to exception page which is not happening.
public ActionResult IsLoginExsit(CustomerDO loginData)
{
if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty(loginData.Password))
{
bool result = Businesss.Factory.BusinessFactory.GetRegistrations().IsLoginExist(loginData.UserName, loginData.Password);
if (result)
{
CustomerDO custInfo = new CustomerDO();
JsonResult jsonResult = new JsonResult();
jsonResult.Data = loginData;
custInfo = Businesss.Factory.BusinessFactory.GetRegistrations().GetCustInfoByUserName(loginData.UserName);
SessionWrapper.SetInSession("CustomerID", custInfo.Id);
SessionWrapper.SetInSession("CustomerFirstName", custInfo.FirstName);
SessionWrapper.SetInSession("CustomerLastName", custInfo.LastName);
return jsonResult;
}
else
{
return RedirectToAction("UnAuthorized", "Exceptions");
}
}
return View();
}
You seem to be invoking this action using AJAX. If you want to redirect this should be done on the client side in the success callback of this AJAX call using window.location.href. So for example you could adapt your action so that in case of error it returns a JSON object containing the url to redirect to:
else
{
return Json(new { errorUrl = Url.Action("UnAuthorized", "Exceptions") });
}
and then inside your AJAX success callback:
success: function(result) {
if (result.errorUrl) {
window.location.href = result.errorUrl;
} else {
...
}
}

mvc3 ajax submission on the controller side. How?

I don't understand once button clicked
How to handle ajax call on the server side so that my DataAnnotation work
and I get success or error message.
<script src="../../../../Content/Scripts/jquery-1.4.4-vsdoc.js" type="text/javascript"></script
<script type="text/javascript">
$(function ()
{
$("#createButton").click(function ()
{
var profile = {
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
Email: $("#Email").val()
};
$.ajax({
url: "/Profile/Create",
type: "Post",
data: JSON.stringyfy(profile),
dataType: "json",
contentType: "Application/json; charset=utf-8",
success: function () {
$("#message").html("Profile Saved.");
},
error: function () {
$("#message").html("Error occured");
}
});
return false;
});
});
</script>
//Server side
public ActionResult Create(string confirmButton, CreateViewModel userVm)
{
if (confirmButton != "Create Profile") return RedirectToAction("Index");
if (!ModelState.IsValid)
return View("Create", userVm);
User user = new User();
Mapper.Map(userVm, user);
_repository.Create(user);
return RedirectToAction("Details", new { id = user.UserId });
}
If I remember correctly (it's been a while since I played with jquery), the success and error are indicative of the return value of the actual HTTP request itself. For example, if you hit a 404, you'd get an error message.
Regardless of whether or not a profile was created successfully through your page logic, if the request itself was processed, then the success message will be hit - you need to interpret the return value yourself at that point.
Try returning a JsorResult in place of redirecting to a view, then client side, parse the JsonResult and act accordingly.
[HttpPost]
public JsonResult DeleteDoc(int Id, int DocCode, SomeObject Model)
{
try
{
// Check annotations stuffs
if (!Model.IsValid) {
var jsonDataM = new { ExitCode= -100, message = "Invalid Model" };
return Json(jsonDataM, JsonRequestBehavior.DenyGet);
}
// My logic in here
var jsonData = new { ExitCode= 0, message = "Everything's ok" };
return Json(jsonData, JsonRequestBehavior.DenyGet);
}
catch (Exception e)
{
var jsonData2 = new { ExitCode= -1, message = "Everything's Ko" + e.Message };
return Json(jsonDat2a, JsonRequestBehavior.DenyGet);
}
}
in the OnSuccess callback you can refer to this with:
<script type="text/javascript">
function MyAjaxCallBack(context) {
var code = context.ExitCode;
if (code != 0) {
alert (context.message);
}
}
</script>
Please note that this code is simplified. When managing the IsValid on Model, I usually iterate del ModelState in order to build up a message.

Resources