How to pass email id via ajax call (not as string), i need to catch that email parameter in spring controller.
$.ajax({
type : "POST",
contentType : "application/json",
data: data,
dataType: "text",
url : "<%=request.getContextPath()%>/methodName";,
success : function(data){
}
});
Java code:
#RequestMapping(value="/methodName/{email}", method =RequestMethod.POST,produces="application/json")
#ResponseBody
public String resetPassword(#PathVariable(value = "email") String email) throws Exception{
//do something
return "success";
}
The below code did the trick.
$.ajax({
type : "POST",
data: {
'email': email
},
url : "<%=request.getContextPath()%>/methodName";,
success : function(data){
}
});
#RequestMapping(value="/methodName", method =RequestMethod.POST)
#ResponseBody
public String resetPassword(#RequestParam(value = "email") String email) throws Exception{
//do something
return "success";
}
Related
I am making an ajax post call to my backing spring controller. I see that the data is saved successfully in the db as a result of post but on the browser console I see that POST throws 404. Also, once the call returns from the spring controller, error function of ajax call is envoked.
Can someone please tell me what I am missing here.
$('#submitMessage').submit(function(e){
e.preventDefault();
var formData = {};
var msg=document.getElementById('iconLeft4-1');
var url = "${context}/wasadmin/support/ajax/send";
formData['comment']=msg.value;
formData['commented_by']='1';
formData['supportId']='1';
formData['userType']='O';
console.log(JSON.stringify(formData));
$.ajax({
type : 'POST',
contentType: "application/json",
url : url,
dataType : 'json',
data:JSON.stringify(formData),
success:function(data,status,xhr){
console.log('saved successfully');
},
error:function(data,status,xhr){
console.log('error occured'); // This gets printed
}
});
Controller
#PostMapping(value="/ajax/send")
public void sendSupportMessage(#RequestBody SupportConversationDTO supportConversationDTO) {
supportConversationService.save(supportConversationDTO);
return;
}
In your ajax request you are using dataType:'json', jQuery’s Ajax-Related Methods Description Says
// The type of data we expect back
dataType : "json",
But from your controller, you are returning void!!!
You need to update your ajax request, remove dataType and update success:function
$.ajax({
type : 'POST',
contentType: "application/json",
url : url,
data:JSON.stringify(formData),
success:function(data) {
console.log('saved successfully');
},
error:function(data,status,xhr) {
console.log('error occured');
}
});
Then change your controller code, return something from it and add #ResponseBody
#PostMapping(value="/ajax/send")
#ResponseBody
public String sendSupportMessage(#RequestBody SupportConversationDTO supportConversationDTO) {
supportConversationService.save(supportConversationDTO);
return "success";
}
i try to pass Parameter from Ajax to RestController to send a Email.
That is the Controller Post Methode to send the Enail
#RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String create(#RequestParam("covere") String covere, #RequestParam("title") String title,
#RequestParam("username") String username, #RequestParam("usernameto") String usernameto) {
try {
mailService.sendMail(covere, title, username, usernameto);
return "sendmail";
} catch (MailException e) {
e.printStackTrace();
}
return "sendmail";
}
That is the Ajax to Call the Post and pass the Variable to send Message
$("#vuta").on("click", function(e) {
var EmailData = {
"covere" : "John",
"title" :"Boston",
"username" :"test#yahoo.fr",
"usernameto" :"test#yahoo.fr"
}
$.ajax({
type: "POST",
url: "/emailsend",
dataType : 'json',
contentType: 'application/json',
data: JSON.stringify(EmailData)
});
});
I have this Error when i send the Email
Required String parameter 'covere' is not
present","path":"/emailsend"}
Thank for help
Your controller is expecting parameters via Query String. You can use $.param to format the object as query string and send it in the URL:
$("#vuta").on("click", function(e) {
var EmailData = {
"covere" : "John",
"title" :"Boston",
"username" :"test#yahoo.fr",
"usernameto" :"test#yahoo.fr"
}
$.ajax({
type: "POST",
url: "/emailsend?" + $.param(EmailData),
dataType : 'json',
contentType: 'application/json'
});
});
I am trying to pass some variables through JSON from JSP to servlet through ajax call. But i am getting null value at servlet side. Please some one help me on to find out where i am making mistake/ what i missed
//JSON
var masterdata = new Object();
masterdata.grn = $('#grn').val();
masterdata.pono = $('#pono').val();
masterdata.podt = $('#podt').val();
//call the servlet to insert the data only when error = 0
if (error != 1){
$.ajax({
url : 'insertserv',
type: 'POST',
dataType: 'json',
data: {test : JSON.stringify(masterdata)},
contentType: 'application/json',
mimeType: 'application/json',
success : function(data) {
alert('Hi');
}
});
}
else{
alert("Save cannot be performed. Please check the entered data!");
}
});
public class insertserv extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("I am inside insert");
String masterdata = request.getParameter("test");
System.out.println("masterdata : "+masterdata);
response.setContentType("text/plain");
}
}
Replace your ajax code with my code...
//JSON
var masterdata = new Object();
masterdata.grn = $('#grn').val();
masterdata.pono = $('#pono').val();
masterdata.podt = $('#podt').val();
//call the servlet to insert the data only when error = 0
if (error != 1){
$.ajax({
url : 'insertserv',
type: 'POST',
dataType: 'json',
data: JSON.stringify({"test" :masterdata}),
contentType: 'application/json',
mimeType: 'application/json',
success : function(data) {
alert('Hi');
}
});
}
else{
alert("Save cannot be performed. Please check the entered data!");
}
});
To get data in servlet
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String json = "";
if (br != null) {
json = br.readLine();
}
JSONObject wholedata= new JSONObject(json);
now the object wholedata has a your json..
if you are using JSON.stringify() then you have to use
BufferedReader in servlet ,
You can use request.getparameter in servlet when you are passing data in URL of servlet.
If your backend is responding with json content then only dataType:"json" works. Try change the response type:
response.setContentType("application/json");
Because your ajax is expecting json from the backend with dataType:"json",.
or vice-versa.
change the dataType to text: dataType:"text", as the response header says response.setContentType("text/plain");. But in this case you have to use JSON.parse() to parse the json string.
//JSON
var masterdata = new Object();
masterdata.grn = $('#grn').val();
masterdata.pono = $('#pono').val();
masterdata.podt = $('#podt').val();
//call the servlet to insert the data only when error = 0
if (error != 1) {
$.ajax({
url: 'insertserv',
type: 'POST',
dataType: 'text', //<------change this
data: {
test: JSON.stringify(masterdata)
},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert('Hi');
}
});
} else {
alert("Save cannot be performed. Please check the entered data!");
}
});
Now my ajax call:
$.ajax({
type: "POST",
url: contextPath +"/action",
cache:false,
dataType: 'text',
data: {Id:Id},
success: function(Result){
alert("in success ***");
dialog.dialog("close");
window.location.href = Result;
} ,
error: function(Result){
alert("in error");
}
});
My Controller code:
#RequestMapping(value="/action", method=RequestMethod.POST)
#ResponseStatus(value=HttpStatus.OK)
public #ResponseBody ModelAndView getApplyTemplatePage(#RequestParam("Id")int cId){
System.out.println("In apply template controller");
System.out.println("the value of id "+cId+" hostname"+hostName+"templateName"+tempName);
return new ModelAndView("applyTemplate");
}
Now i want to redirect to applyTemplate.jsp page.
My Requirement is using by ajax call how to redirect to another jsp page ?
You can send a ResponseEntity with location header back in spring and redirect accordingly.
public ResponseEntity<?> getApplyTemplatePage(#RequestParam("Id") int cId, UriComponentsBuilder b) {
UriComponents uriComponents = b.path("/applyTemplate.jsp").build();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(uriComponents.toUri());
return new ResponseEntity<Void>(headers, HttpStatus.OK);
}
and in the ajax call, you can get the location header and redirect accordingly.
success: function(data, textStatus, xhr) {
window.location = xhr.getResponseHeader("Location");
}
I call the webservice using jquery, whenever i call, i get the error result only.
My server code:
[WebService(Namespace = "http://xxx.xample.org")]
[WebServiceBinding( Name ="XService", Namespace="http://xxx.xample.org/XService.asmx?")]
[System.Web.Script.Services.ScriptService]
public class AathiService : System.Web.Services.WebService
{
[WebMethod]
public string IsValidUser(string UserName , string Password)
{
// process
return result;
}
}
}
Then i call the service using jquery like this.. .
$("#okButton").click(function () {
// CALLING WEBSERVICE
var param = { UserName: 'xxxx', Password: 'xxxxx' };
$.ajax({ type: "POST", contentType: "application/json;charset=utf-8", data: JSON.stringify(param),
url: "http://xxx.xample.org/xService.asmx/IsValidUser", dataType: "json", async: true,
success: function () { alert("success"); }, error: function (xhr,msg) { alert(msg + " " + xhr.responseText); }
});
});
I am always get the error part. i doesn't know what i am done .
in your webmethod you are expecting a "string" as return type , but you call the ajax call with datatype JSON
this should solve your problem:
[WebMethod]
public JsonResult IsValidUser(string UserName , string Password)
{
// process
return Json(result);
}
Just change async: false. problem solved