JQuery/AJAX call is not hitting Spring MVC controller - javascript

I am trying to verify username and other fields while creating a change password page.The problem is AJAX call in Jquery script is not hitting my controller.i tried giving hard coded path also in url field of the ajax request.
Below is my Script
this checkUname function is triggering on onblur event from one of the input field.
<script type="text/javascript">
function checkUname()
{
// get the form values
var uName = $('#username').val();
var secQues = $('#secQues').val();
var secAns = $('#secAns').val();
var dataObject = JSON.stringify({
'uName' : uName,
'secQues': secQues,
'secAns' : secAns
});
$.ajax({
url:"validateCredentials.do" ,
type: "POST" ,
data: dataObject ,
contentType: "application/json; charset=utf-8" ,
dataType : 'json' ,
success: function(response)
{
alert(response);
} ,
error: function()
{
alert('Error fetching record.... Sorry..');
}
});
}
</script>
This is my MVC controller
#Controller
public class ArsController
{
#RequestMapping(value="validateCredentials.do", method = RequestMethod.POST)
public String changePass(#RequestParam("uName") String uName ,#RequestParam("secQues")String secQues,
#RequestParam("secAns") String secAns)
{
System.out.println("AJAX request");
Users dummyUSer = null;
String msg = null;
try
{
dummyUSer = servObj.findUser(uName);
}
catch (ArsException e)
{
System.out.println("error occurred while validating user data during password change");
e.printStackTrace();
}
if(dummyUSer == null)
{
msg = "No user exists with this username";
}
else
{
if(!secQues.equals(dummyUSer.getSecQues()))
{
msg = "Security question is not correct";
}
else
{
if(!secAns.equals(dummyUSer.getSecAns()))
{
msg = "Security answer does not match";
}
}
}
return msg;
}

Instead of using RequestParam in controller, you should use String. Because when we are posting JSON data it will not come as individual parameters in Request, instead it will be received as String in your controller. Once you get the String convert it to JSON object and then get your values accordingly.

try remove content-type and data-type.
You are not sending a json that should be parsed in a object, you are sending controller's parameters.
The way to do that is using an object in the Ajax 's data (as you did) but without the content-type or data-type that saying "I'm sending one json parameter"

Related

Trying to make an Ajax call to a web form method and getting an internal server error. I have tried almost all solutions to similar questions

The function getClientData() gets called from one of the anchor tags in a grid's column. The anchor tag has a couple of Data-Tags which are passed to the code behind method. I have to perform some DB operation through these parameters but before that I wanted to make sure if this prototype would work.
This is how the anchor tag looks:
Show
This is my Javascript method:
function getClientData() {
//var dataValue = { "keyData": this.event.target.getAttribute("data-kt"), "valueData": this.event.target.getAttribute("data-kv")};
$.ajax({
type: "GET",
url: "Clients.aspx/GetClientData",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ keyData: this.event.target.getAttribute("data-kt"), valueData: this.event.target.getAttribute("data-kv")}),
dataType: 'json',
error: function (error) {
alert(error.statusText);
},
success: function (result) {
alert("Success: " + result );
}
});
}
I put a break point here and it never gets triggered. This is my web method in the code behind file:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string keyData, string valueData)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}
This is the URL that gets created for the POST request "http://localhost:60825/Clients.aspx/GetClientData?{%22keyData%22:%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22,%22valueData%22:%221p7q9%22}". Please let me know if I am doing something wrong.
I am not sure how you configured routing but based on your API method (code behind) your data should be formatted in following manner:
Method 1:
http://localhost:60825/Clients.aspx/GetClientData?keyData=Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy&valueData=1p7q9
As you can see, instead passing stringified JSON object I am sending data in format of query string where keyData and valueData has corresponding values.
Method 2:
If you prefer to send stringified JSON you can modify your Payload in URL like this:
http://localhost:60825/Clients.aspx/GetClientData?data=%7BkeyData%22%3A%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22%2C%22valueData%22%3A%221p7q9%22%7D
Here I am sending stringified JSON as data parameter in query string. For that purpose your code behing method needs to be like this:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string data)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}

Can i send java object in a json response

For example i have java class post:
public class Post{
String title;
String text;
}
If i create an instance of this class and convert it into ajax response in my servlet controller
#RestController
public class AjaxNewsController {
#JsonView(Views.Public.class)
#PostMapping(value = "/getPost")
public AjaxResponseBody getSearchResultViaAjax(#RequestBody AjaxPostResponse postId) {
AjaxResponseBody result = new AjaxResponseBody();
result.setCode("200");
result.setMsg("found POST");
result.setResult(post);
return result;
}
}
My question is: can i retrieve post fields title and text with javascript on a client side and if i can then how?
Here is an example of console with my response in browse
console
but how can i extract my post with fields in ajax and jquery?
UPD
after some reaserach i found that somehow my serlvet doesn't convert my java pojo into json. How should i do it?
UPD2
my request sends normaly but serlvet doesn't convert POST class into json.
here is my javascript :
function likePost(postId,ratingElem, ratingChange) {
var search = {}
search["postId"] = postId;
search["rating"] = ratingChange;
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url : "likePost",
data : JSON.stringify(search),
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
changeRating(ratingElem,data.post.getTopic());
},
error : function(e) {
console.log("ERROR: ", e);
changeRating(ratingElem,'error');
},
done : function(e) {
console.log("DONE");
enableSearchButton(true);
}
});
}
status and message is fine but result is empty.
try it:
var req = new XMLHttpRequest();
req.open('POST', 'your_url', false);
req.send(null);
if(req.status == 200)
dump(req.responseText);
and if you want to get data from another domain please read cors
So i solved my problem. I use com.fasterxml.jackson.core so i just need to mark fields in my class that i want to convert into json with #JsonView annotation like
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "post_id",
unique = true, nullable = false)
#JsonView(Views.Public.class)
private Integer postId;
Everything that marked will be converted.

Controller Action method return string or Redirect to another action with ajax post request

I am calling MVC action method through jquery ajax post. This action method will either return a string value or if certain condition in action method is true it will redirect to another action method. The problem is whenever i am trying to redirect to another action method the ajax post is executing the error block and whenever the action method is returning a string value it works fine. I don't want to use html form post. Below is my code:
function VerifyCreds() {
$.ajax({
type: "POST",
url: "/Login/Verify",
data: '{Username: "' + $("#txtUsername").val() + '",Password: "' + $("#txtPassword").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
public ActionResult Verify(string Username, string Password)
{
string Response = "0";
EmployeeEntities ent = new EmployeeEntities();
var val = ent.VerifyUser(Username, Password);
Response = val.FirstOrDefault().ToString();
if (Response == "1")
{
return this.RedirectToAction("LandingPage");
}
return Content(Response);
}
public ActionResult LandingPage()
{
return View();
}
You are explicitly specifying json as the data type. that means, your ajax method expects the response from the server as a json string. The jQuery ajax method will use JSON.parse method to create a JavaScript object from this json string and pass it to the callback. When you do a redirect from server, it is not returning a 200 OK response back, but a 302 redirect response back and browser will usually makes a new call to the location header value of the response. You are getting the error callback of the ajax method because the server is returning some string which cannot be safely converted to a JavaScript object using JSON.parse. (My guess is that the response for the LandingPage call!. Check the network tab to see what response is coming)
If you absolutely want to handle this situation, you may better return a proper JSON structure in both the cases and inspect this json data at client side and do a redirect as needed.
I also suggest you to use the appropriate types. Use int instead of storing a number in a string variable.
public ActionResult Verify(string Username, string Password)
{
var ent = new EmployeeEntities();
var val = ent.VerifyUser(Username, Password);
var response = val.FirstOrDefault();
if (response == 1)
{
return Json(new { status="redirect", url = Url.Action("LandingPage")});
}
return Json(new { status="success", message = "Valid login" });
}
and in the success event of your ajax call, inspect this json data and based on the status property, do a redirect or show a message to the user.
success: function (response) {
if(response.status==="redirect")
{
window.location.href = response.url;
}
else
{
alert(response.message);
}
},
You can also totally remove dataType: "json", from your ajax call. jQuery will intelligently guess the type based on the response headers and use that. Since we are explicitly returning Json from our action method, the response Content-Type header value will be application/json

How I send the result of the AJAX back to the JSP?

I post some via AJAX in my servet from my jsp
$.ajax({
url: 'myServlet?action=FEP',
type: 'post',
data: {machine: i, name: txt}, // i, txt have some values.
success: function (data) {
alert('success');
}
});
and in my Serlvlet
String jspAction = request.getParameter("action");
//...
if(jspAction.equals("FEP")){
int idMachine = Integer.parseInt(request.getParameter("machine"));
String name = request.getParameter("name");
double value = actions.getValue(idMachine, name); //<-- this variable I want to send it back to the JSP.
}
The data are sent succesfully. However I haven't understand how I send back the vaule to the jsp..
returning a string would go as follows:
response.getWriter().write("a string");
return null;
If you want to return json, you can use many libraries like: http://www.json.org/
This would result in something like following code:
response.setContentType("application/json");
JSONObject jsonObject = new JSONObject();
double aDouble = 38d;
jsonObject.put("returnValue", aDouble);
response.getWriter().write(jsonObject.toString());
return null;
Use
response.getWriter().write(value);
return null;
And in your ajax success block access the value.
See the following link for more understanding http://www.javacodegeeks.com/2014/09/jquery-ajax-servlets-integration-building-a-complete-application.html

Using reCAPTCHA with Ajax in Spring MVC

I am trying to use google reCAPTCHA service with spring MVC.But I am getting this error on console:
http://localhost:8080/spapp/ajaxtest.htm?name=frfr&surname=frfr&phone=ededeā€¦nGi3CCrD9GprYZDn8VHc-pN--SK-u_xoRKOrnRc_ISQh&recaptcha_response_field=1404 Failed to load resource: the server responded with a status of 400 (Bad Request)
Here is My AJAX JavaScript Codes:
$(document).on("click","button#save",function(){
var name=$("input#name").val();
var surname=$("input#surname").val();
var phone=$("input#phone").val();
var recaptcha_challenge_field=$("#recaptcha_challenge_field").val();
var recaptcha_response_field=$("#recaptcha_response_field").val();
var error=0;
if(name==""){
$("label#stateName").html("First Name field must be filled!");
error=1;
}
if(surname==""){
$("label#stateSurName").html("Last Name field must be filled!");
error=1;
}
if(error==0) {
$("div#addResult").html("<img src=\"resources/images/loading.gif\" style=\"max-width:50px;max-height:50px;margin-left:250px;\"/>");
setTimeout(
function()
{
$.ajax({
url:"ajaxtest.htm",
data:{name:name,
surname:surname,
phone:phone,
recaptcha_challenge_field:recaptcha_challenge_field,
recaptcha_response_field:recaptcha_response_field},
success:function(response){
$("div#addResult").html(response);
}
});
}, 2000);
}
});
Here My Controller Method:
#RequestMapping(value = "/ajaxtest", method = RequestMethod.GET)
public #ResponseBody String ajaxCRUDPerson(
#ModelAttribute Person person,
ModelMap model,
#RequestParam(value="id") String id,
#RequestParam(value="name") String name,
#RequestParam(value="surname") String surname,
#RequestParam(value="phone") String phoneNumber,
#RequestParam("recaptcha_challenge_field") String challangeField,
#RequestParam("recaptcha_response_field") String responseField,
ServletRequest servletRequest) {
String remoteAddress = servletRequest.getRemoteAddr();
ReCaptchaResponse reCaptchaResponse = this.reCaptcha.checkAnswer(remoteAddress,challangeField, responseField);
String result = "";
if(reCaptchaResponse.isValid()){
if(StringUtils.hasText(person.getId())) {
person.setName(name);
person.setSurname(surname);
person.setPhoneNumber(phoneNumber);
personService.updatePerson(person);
result+="The person has been updated successfully! "+person.getName();
} else {
person.setName(name);
person.setSurname(surname);
person.setPhoneNumber(phoneNumber);
personService.addPerson(person);
result+="The person has been inserted successfully!";
}
model.addAttribute("personList", personService.listPerson());
return result;
}else{
return "Invalid answer!";
}
}
I couldnt understand where is wrong.
How Can I fix this error!
Thanks
RequestMapping "/ajaxtest" is not matching with the url passed in the Ajax call.
Use "ajaxtest" instead of "ajaxtest.htm" in the Ajax call.
Reference: Spring MVC based reCaptch with live demo http://www.srccodes.com/p/article/33/integrate-free-anti-bot-service-recaptcha-with-spring-mvc-application

Categories

Resources