redirect to another jsp page - ajax

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'

Related

Spring Ajax file upload

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:)

How to send boolean result to ajax call

I want to send Boolean result in ajax call.
Ajax call
function myMethod() {
$.ajax({
type : "GET",
url : myurl
dataType : "json",
contentType: "application/json",
crossDomain: true,
success : function(data) {
alert("success :"+data);
},
error : function(data) {
alert("Fialed to get the data");
}
});
}
Controller method from where I want to send Boolean result.
#RequestMapping(value = "/myMethod", method = RequestMethod.GET)
#ResponseBody
public boolean myMethod(empId) {
flag = false;
try {
if (empId != null)
newName = Employee.getName(empId);
else
newName = Employee.getName();
} catch (Exception e1) {
flag = true;
System.out.println("flag :" + flag);
e1.printStackTrace();
}
return flag;
}
i want to send the Boolean flag result to ajax call.
How do i send it. dont mind about the logic .. I just want to know how can i send boolean result to ajax call. Please help .
Ajax uses HTTP which is a text protocol and has no concept of booleans. However, you can return the strings "1" or "0" to represent your boolean values.
Then, in your "success" callback:
success : function ( data ) {
if ( data * 1 ) {
// true result
} else {
// false result
}
}
Without passing the Boolean value to the Ajax call, you can do some thing like this using a map. Using this map you can send anything rather than only limiting to Boolean values.
#RequestMapping(value = "/myMethod", method = RequestMethod.GET)
#ResponseBody
public Map<String, Object> myMethod(empId)
{
flag=false;
try {
if(empId != null)
newName = Employee.getName(empId);
else
newName = Employee.getName();
} catch (Exception e1) {
flag=true;
System.out.println("flag :"+flag);
e1.printStackTrace();
}
final Map<String, Object> map = new TreeMap<String, Object>();
map.put("flagdata", flag);
return map;
}
Then you can access this 'flagdata' object in the Ajax call.
Your Ajax code will be some thing like this.
$.ajax({
type : "GET",
url : myurl
dataType : "json",
contentType: "application/json",
crossDomain:true,
success : function(data) {
alert("success :"+data.flagdata);
},
error : function(data) {
alert("Fialed to get the data");
}
});
Hope it helps.!

ajax call to servlet and redirect to jsp

Here in the below code i want to call a servlet through ajax and then i redirect the data from servlet to jsp.ajax call to servlet is working fine but the problem is redirecting to the jsp page is not displayed in the browser and the same jsp page is displayed when i used with javascript code without ajax.
javascript ajax code in the jspfile:
function generate(){
...
...
var url="RedirectServlet";
var ajax=new AJAXInteraction(url,"RedirectServlet");
var param ="FD="+FD+"&TD="+TD+"&actionid="+status+"&usercode="+usercode+"&action=reports"+"";
ajax.send(param);
....
}
function AJAXInteraction(url, actionType) {
this.url = url;
var req = init();
var actionRequested = actionType;
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest () {
if (req.readyState == 4) {
if (req.status == 200) {
if(actionRequested=="TestDelegation") {
PostProcess1(req.responseXML);
}
}
}
}
this.send = function(param) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(param);
}
}//end of AJAX Interaction object.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("calling doPost() ");
response.setContentType("text/html;charset=WINDOWS-1256");
String action=request.getParameter("action");
System.out.println(action);
if(action.equals("reports")){
System.out.println("inside reports");
//Getting values from Reports_arb.jsp
String Fromdate=request.getParameter("FD");
String Todate=request.getParameter("TD");
String status=request.getParameter("actionid");
String usercode=request.getParameter("usercode");
//placing given values in a session
request.setAttribute("FD", Fromdate);
request.setAttribute("TD", Todate);
request.setAttribute("actionid", status);
request.setAttribute("usercode", usercode);
//Redirecting to showReport_arb.jsp
//response.sendRedirect("showReport_arb.jsp");
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/sample.jsp").forward(request, response);
You need to understand the fact that when you send http request from ajax, it means that you are sending the request in separate thread and not in the main thread (the page itself from where you are sending the request). So redirection at the servlet will not reflect at the client end. In order to achieve this, send back the URL to which you want to redirect as a response to request and on success method of ajax simply use java script window.location(URL);
At servlet
JSONObject jobj = new JSONObject()
String urlToRedirect = "test.jsp";
jobj.put("url",urlStr);
response.getWriter().write(jobj.toString());
At client end
$.ajax({
url: 'servletName',
data: {
userID: selectedID
},
type: 'post',
success: function(data){
window.location = data.url;
}
});
Instead of creating the request and response object, use jquery Ajax. It is very simple to use.
/* Send the data using post and put the results in a div */
$.ajax({
url: "/YourServlet",
type: "post",
data: values,
success: function(){
alert("success");
$("#result").html('submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});

Setting up .Net MVC http error codes for ajax calls

I'm trying to setup my controllers so that they can use http error codes to send the responses to ajax calls. So for example I have my login ajax call and controller action:
[System.Web.Mvc.HttpPost, System.Web.Mvc.AllowAnonymous]
public ActionResult Login(string userName, string password, bool rememberMe, string returnUrl)
{
[...]
var loginError = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("Lorem ipsum 2 " + ErrorMessages.LOGINERROR),
ReasonPhrase = "Lorem ipsum 2 " + ErrorMessages.LOGINERROR
};
throw new HttpResponseException(loginError);
}
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "text",
success: callBack,
error: function () { console.log("Error..."); },
statusCode : {
401: function (result) {
console.log("Login failed (401): " + result);
}
}
});
I'm thinking there are a couple of things I'm not doing right, if someone can point them out that would be lovely!
Thanks!
Look at this solution: ASP.NET MVC Ajax Error handling
Darin Dimitrov write very nice solutions with action filter:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
Then you could write your client error handling for all status codes and use it for ajax requests.
Instead of throw exception just return ActionResult that provide some content and setup response code. For your case you can create something that I call ExtendedJsonResult:
public class ExtendedJsonResult : JsonResult
{
public ExtendedJsonResult(object data)
{
base.Data = data;
}
public int StatusCode { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = this.StatusCode;
base.ExecuteResult(context);
}
}
and then in controller
return new ExtendedJsonResult("Some error")
{
StatusCode = 401,
};
You can also just return existing HttpStatusCodeResult.

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 {
...
}
}

Resources