after getting request from ajax to controller i am not able to move to next page through ModelAndView("/authenticationError.jsp");
controller code
#RequestMapping(value = "/ProcessReject,method = RequestMethod.POST" )
public ModelAndView Reject(#RequestParam(value = "StatusComments") String StatusComments,
#RequestParam(value = "ruleIndex") String ruleIndex,
#RequestParam(value = "country") String country,
HttpSession session) throws Exception {
ModelAndView mav ;
System.out.println("StatusComments "+ StatusComments);
System.out.println("ruleIndex "+ ruleIndex);
System.out.println("country "+ country);
String quicklookid = (String) session.getAttribute("quicklookid");
//rejectRuleBusinessLogic.reject(ruleIndex, country, quicklookid, StatusComments);
mav = new ModelAndView("/authenticationError.jsp");
return mav;
Ajax code
function showRejectStatusMsg(value1, value2)
{
$.ajax({
type: "POST",
cache: false,
url: "ProcessViewRule.ncr",
data:"ruleIndex=" +value1 +"&country="+value2,
success: function(response) {
},
error : function(e) {
alert('Error in response...' + e);
}
});
jsp code -
<a href="javascript:showRejectStatusMsg(<c:out value='${List.ruleindex}'/>, '<c:out value="${List.country}"/>')" id="rejectLink" class="navlink" >Reject</a>))
You are doing it wrong..You need to write .jsp and can set the view as
mav.setViewName("list");
Basically
new ModelAndView("welcomePage", "WelcomeMessage", message);
is shorthand for
ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);
Related
In my ASP.NET framework MVC project I must send below two data (first data is a list of string and second data is a GUID) with ajax to the action in controller:
0: "{Key:'052c5941-233a-4bd2-80e1-7cfffa34ca44',Value:'Salary1'}"
1: "{Key:'00000000-0000-0000-0000-000000000004',Value:'Salary2'}"
2: "{Key:'00000000-0000-0000-0000-000000000005',Value:'Salary3'}"
3: "{Key:'00000000-0000-0000-0000-000000000003',Value:'Salary4'}"
4: "{Key:'00000000-0000-0000-0000-000000000001',Value:'Salary5'}"
5: "{Key:'00000000-0000-0000-0000-000000000002',Value:'Salary6'}"
and
"6a580cf1-2f05-4621-8a67-8fe0bdd559c2"
My action is as below
public JsonResult DigestFile(List<string> value1, string pointId)
{
....
}
How can I do this? Any help will be appriciated!
You can use HTTP post as the following code to do it, you just creat a class with Key and Value, and use it in Controller with a String variable, on a HTTP post Function.
I am not expert in C# I did translate online from my VB code that work well.
In your Views (.cshtml) :
<input id="Button1" type="button" value="button" onclick="SaveMe()" />
<script>
function SaveMe() {
var GUID = '6a580cf1-2f05-4621-8a67-8fe0bdd559c2';
// Creat Object
var lineItems = new Object();
lineItems.Entrys = new Array();
// Example Filling your object, but of course you can get data from another place ...
lineItems.Entrys[0] = new Object({ Key: '052c5941-233a-4bd2-80e1-7cfffa34ca44', Value: 'Salary1' });
lineItems.Entrys[1] = new Object({ Key: '00000000-0000-0000-0000-000000000004', Value: 'Salary2' });
lineItems.Entrys[2] = new Object({ Key: '00000000-0000-0000-0000-000000000005', Value: 'Salary3' });
$.ajax({
type: "POST",
url: "/Home/AjaxMethodDigestFile",
data: JSON.stringify({ Entrys: lineItems.Entrys, GUID: GUID }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) { alert(response.message); },
failure: function (response) { alert("failure"); },
error: function (response) { alert("error"); }
});
}
</script>
In your Models:
namespace MyModel1.ViewModel
{
public class MyClass1
{
public string Key { get; set; }
public string Value { get; set; }
}
}
In your Controllers:
[HttpPost]
public JsonResult AjaxMethodDigestFile(ICollection<MyModel1.ViewModel.MyClass1> Entrys, string GUID)
{
string message = "";
int counter = 0;
foreach (var entry in Entrys)
{
// How to use this data example
string Key = entry.Key;
string Value = entry.Value;
counter += 1;
message += Value + ": " + Key + Constants.vbCrLf;
}
// The following lines are not necessary, it's just an example code to know what happen and return it to client side ...
if (counter > 0)
message = counter.ToString() + " Entrys received" + Constants.vbCrLf + message;
else
message = "no entrys";
var response = new { counter, message };
return Json(response);
}
I want to get data about my user from ajax request. But it never logs anything, which means it never reaches to success part of ajax request.
This is my controller
#Controller
#RequestMapping(value = "/api/profile")
public class ProfilController {
#Autowired
public UserService userService;
#RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
public ResponseEntity<UserDTO> showData(#PathVariable String username) {
User u = userService.findByUsername(username);
if(!userService.findAll().contains(u))
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(new UserDTO(u), HttpStatus.OK);
}
}
And this is my java script file.
$(document).ready(function() {
console.log(localStorage.getItem('loggedIn'));
var usrnm = localStorage.getItem('loggedIn');
$.ajax({
url: "http://localhost:8080/api/user/login/check/"+usrnm,
type: "GET",
headers: {"Authorization": localStorage.jwt},
success: function(data) {
console.log('success');
}
})
$.ajax({
url: "http://localhost:8080/api/profile/show/"+usrnm,
type: "GET",
success: function(data) {
console.log('This part is not executed');
}
})
});
I am new to Spring, actually I am new to programming so sorry if this question is not well formatted
You may have an error in the showData function. You should do the following:
#PathVariable("username") String username
Try to remove this.
#Controller
#RequestMapping("/api/profile") // fixed this!!! remove `value = `
public class ProfilController {
#Autowired
public UserService userService;
#RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
public ResponseEntity<UserDTO> showData(#PathVariable String username) {
User u = userService.findByUsername(username);
if(!userService.findAll().contains(u))
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(new UserDTO(u), HttpStatus.OK);
}
}
Am getting values in Ajax page
function GetInfoDivision()
{
var data = $("#storeName").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "hello",
data : JSON.stringify(data),
dataType : 'json',
//timeout : 100000,
success : function(map) {
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
But Controller page getting null value ...Ajax data value not passed to the controller
#RequestMapping(value="/hello", method = RequestMethod.POST)
public String employeeLogin(ModelMap model, HttpServletRequest request) {
String sname = request.getParameter("storeName");
System.out.println("s="+sname);
shopModel s = new shopModel();
s.setStoreName(sname);
//boolean result = employeeService.employeeLogin(employee);
boolean result =false;
if(result == true){
model.addAttribute("message", "Successfully logged in.");
}
else
{
model.addAttribute("message", "Username or password is wrong.");
}
return "redirect:index.jsp";
}
You should use the #RequestBody annotation in the parameter of the controller function.
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html
#Autowired
private HttpServletRequest request;
#RequestMapping(value="/hello", method = RequestMethod.POST)
public String employeeLogin(#RequestBody ModelMap model) {
If storeName is just a string then you can use #RequestParam
#RequestMapping(value="/hello", method = RequestMethod.POST)
public String employeeLogin(ModelMap model, HttpServletRequest request,
#RequestParam(value = "storeName", required = false) String storeName) {
String sname = storeName;
}
and in Ajax call you can have call like
url : "hello" + "?storeName=" + data
and remove below property in Ajax call
data : JSON.stringify(data),
Your Ajax will look like below:
function GetInfoDivision()
{
var data = $("#storeName").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "hello" + "?storeName=" + data,
dataType : 'json',
//timeout : 100000,
success : function(map) {
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
#RequestMapping(value = "hello", method = RequestMethod.POST)
#ResponseBody
public String methodname(#RequestParam("data") String data) {
...
return "";
}
When user select any value from drop down, then Ajax has to call server and return some values through JSON object.
Here is my Ajax code
//AJAX Security
$('#ddlSecurityLevel').change(function () {
if ($('#ddlSecurityLevel').val() !== 'None') {
$.ajax({
type: 'POST',
url: 'AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=1&ReportName=TotalSales',
contentType: 'application/json; charset=utf-8',
data: 'json',
//dataType: JSON.stringify(Data),
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
//alert("hello");
alert(result.d); // output UNDEFINED
}
function AjaxFailed(result) {
alert("Error");
alert(result.status + ' ' + result.statusText);
}
}
});
Asp.net C# code
public class GetResult
{
public string removedReportName { get; set; }
public string removedColumnNames { get; set; }
public string removedFilterNames { get; set; }
}
public partial class AjaxSecurity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string securityLevelOrUser = Request["securityLevelOrUser"].ToString();
if (securityLevelOrUser.Equals("SecurityLevel"))
{
string jsonString = js.Serialize(getResultBySecurityLevel(Request["SecurityKey"], Request["ReportName"]));
Response.Write(jsonString);
}
else
{
}
}
private GetResult getResultBySecurityLevel(string securityLevel,string reportName)
{
GetResult getResult = new GetResult();
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ReportHide,RColumnName,RFilterName FROM SecurityLevelDetails WHERE SecurityLevel=#SecurityLevel and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#ReportName", reportName);
cmd.Parameters.AddWithValue("#SecurityLevel", securityLevel);
con.Open();
SqlDataReader rd=cmd.ExecuteReader();
while(rd.Read())
{
getResult.removedReportName = rd["ReportHide"].ToString();
getResult.removedColumnNames = rd["RColumnName"].ToString();
getResult.removedFilterNames = rd["RFilterName"].ToString();
}
}
return getResult;
}
}
When I run my Asp.net code with following parameter, It returns values in browser
URL
http://localhost:55047/AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=4&ReportName=TotalSales
Response.Write
{"removedReportName":"1","removedColumnNames":"ItemLookupCode,Department","removedFilterNames":"ExtendedDescription,DepartmentName"}
But the output alert is Undefined
Comment data:'json' and Remove d from alert(result.d);
To access the data in js alert you can write like this,
function AjaxSucceeded(result) {
if(result!=null)
{
alert(result[0].removedReportName +"," result[0].removedColumnNames);
}
}
In your Page_Load method, you need to clear out the output and write your own,
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
Please check this link, this is what you need
I am trying to implement an ajax call using jquery.when i am submitting the call, it is throwing 400 Bad Request..Not sure where i am doing wrong in my ajax call..Need help in fixing this..
submitHandler:function(form){
var emailSub = $("#emailSubTxtArea").val();
var emailBody = $("#emailBodyTxtArea").val();
if(confirm("You are about to send Email Communication, Are you sure..?")){
$.ajax({
type: "POST",
url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
dataType: "json",
//cache:false,
contentType: "application/json; charset=utf-8",
data:JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}),
success:function(data)
{
console.log("Sending Email Notification was success.");
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t
+ m);
}
}
});
}
return false;
}
my Controller code:
#RequestMapping(value="/sendEmailMessage",method=RequestMethod.POST)
public ModelAndView sendEmailCommunication(#RequestParam("emailSubject") String emailSubject,#RequestParam("emailMsg") String emailBody,HttpServletRequest request){
ModelAndView view = null;
StringBuffer sMsg = new StringBuffer();
StringBuffer eMsg = new StringBuffer();
boolean isAdmin = false;
try{
String loggedInUser = request.getHeader("sm_user").trim();
isAdmin = getUserAdminRights(request);
if(isAdmin){
boolean status = emailService.sendEmailCommuncation(emailSubject,emailBody);
if(status){
sMsg.append(" Sending SiteMinder Notification Email was Success.");
}
else{
eMsg.append(" Oops! Something went wrong while sending Email Notification. Pls check logs");
}
}
else{
view = new ModelAndView("redirect:/web/utilities/not_authorized");
return view;
}
}
catch(Exception ex){
ex.printStackTrace();
eMsg.append("Oops! Something went wrong while sending Email Notification. Pls check logs");
}
view = new ModelAndView("EmailCommunication");
view.addObject("isAdmin", isAdmin);
view.addObject("sMsg", sMsg.toString());
view.addObject("eMsg", eMsg.toString());
return view;
}
I am really beating my head for last 4 hrs..help needed .
thanks..
You need quotes around your data keys. Change emailSubject: emailSub,emailMsg : emailBody to "emailSubject" : emailSub, "emailMsg" : emailBody.
You're also missing a closing } at the very end of your submitHandler, could just be a paste error?
dont stringify the data
Change
data:JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}),
to
data:{emailSubject : emailSub,emailMsg : emailBody},
i made the changes to my ajax call and the controller which now user #RequestBody and now it is working fine...
my ajax code:
submitHandler:function(form){
var jsonObj = getData();
if(confirm("You are about to send Email Communication, Are you sure..?")){
$.ajax({
type: "POST",
url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
dataType: 'json',
cache:false,
headers: {
'Content-Type': 'application/json'
},
data:JSON.stringify(jsonObj),
//data: ({emailInfo : JSON.stringify({emailSubject:emailSub,emailMsg:emailBody})}),
success:function(response)
{
response.html();
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t
+ m);
}
}
});
}
return false;
}
function getData(){
var object ={
emailSubject : $("#emailSubTxtArea").val(),
emailMsg : $("#emailBodyTxtArea").val()
};
return object;
}
controller:
#RequestMapping(value="/sendEmailMessage",method=RequestMethod.POST)
public ModelAndView sendEmailCommunication(#RequestBody EmailReqInfo emailInfo){
ModelAndView view = null;
StringBuffer sMsg = new StringBuffer();
StringBuffer eMsg = new StringBuffer();
boolean isAdmin = false;
try{
String loggedInUser = request.getHeader("sm_user").trim();
isAdmin = getUserAdminRights(request);
String emailSubject = emailInfo.getEmailSubject();
String emailMsg = emailInfo.getEmailMsg();
--
----
domain:-
public class EmailReqInfo implements Serializable
{
private static final long serialVersionUID = 1L;
private String emailSubject;
private String emailMsg;
//getters and setters
}