Changing pages spring boot application - javascript

I having problem changing pages. So what I have is a button and when that user press that button a ajax Post is called. Here the example:
$.ajax({
contentType: "application/json",
type: "POST",
data: JSON.stringify(project),
url: "/saveProject",
success: function (data) {
console.log('done');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error while post');
}
});
#RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public #ResponseBody
String saveProject(#RequestBody Project newProject, Authentication authentication) {
projectService.saveProjectNew(newProject, authentication);
return "mywork.html";
}
So in the end I want to be redirect to mywork.html from the page I'm currently on. However nothing happens and I stay on same page. I'm probably missing something that I don't know. Quiet new to this.

To redirect the page into the mywork.html
You need to write the code once you get the response from the Ajax call
So under the success function of Ajax you should use
windows.location.href = "Your context path"+"/mywork.html";
Please refer the reference code below:
$.ajax({
contentType: "application/json",
type: "POST",
data: JSON.stringify(project),
url: "/saveProject",
success: function (data) {
windows.location.href = "Your context path"+"/mywork.html";
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error while post');
}
});
Here the spring web client code will not divert the call to the mywork.html.
All the call will be diverted only through the Ajax call.
return "mywork.html";
This code is only used to model your response which been retrieved after calling the endpoint.

Http redirection could be triggered from both the back-end as well as the front-end ajax code that you have posted.
For the redirection to work from the ui , you can add the window redirection like #Anurag pointed out in his answer on the ajax success callback.
But in your example you are trying to redirect the user to a new page from the backend endpoint itself. So provided that you already have a controller returning the view for the mapping /mywork.html in order for the redirect to work from the spring backend side , you need to do the following :
#RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public String saveProject(#RequestBody Project newProject, Authentication authentication) {
projectService.saveProjectNew(newProject, authentication);
return "redirect:/mywork.html";
}
or using ResponseEntity like :
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(newUrl));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
In your code you were using the annotation #ResponseBody for the controller method which basically makes the endpoint a rest endpoint returning json by default. So , for redirection to work remove the annotation and make it a normal controller method returning view.
Still if you want to redirect from a rest endpoint then use HttpServletResponse like :
#RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public #ResponseBody String saveProject(#RequestBody Project newProject, Authentication authentication, HttpServletResponse response) {
projectService.saveProjectNew(newProject, authentication);
response.sendRedirect("url-here");
}
For more information Link.

Related

How to get response back from the REST API and perform actions from jquery ajax call?

I am learning JS, jquery, and trying to build a login page and after giving the credentials to my application URL I should get a response back and I should be able to perform actions accordingly.
Something like: if the response is "success" then I should get an alert for success and redirect to another page (not sure how to do that) and if the response is "fail" I should throw an alert.
Below is the relevant snippet from my js file:
$.ajax({
url: "http://localhost:8588/api/userLogin",
type: "POST",
data: credentials,
dataType: "json",
contentType: 'application/json',
success: function(response) {
alert(response);
}
});
And my java controller method snipped annotated with #RestController:
#PostMapping(value = "/userLogin", consumes = "application/json")
public String userLogin(#RequestBody UserRequest userRequest) {
System.out.println(userRequest.getUserId()+ " "+ userRequest.getPassword());
User user = userService.getUser(userRequest);
return (user != null) ? "succeess" : "fail";
}
I am not getting any error
I am able to call the API but not getting the response back on UI. What am I missing?
I've taken your code and simulated simple case like yours. Most of the code looks right but as you've said there are no errors in the console and no response to client so there's problem got to be somewhere. There are certain things you've not specified here, so for more context for other people I am assuming UserRequest as
public class UserRequest {
public String username;
public String password;
}
and for the ajax request data I'm using
JSON.stringify({username: "developer", password:"pass"})
Now, I'm getting 200 response code with success message in alert at client side. Let me know if any error pops up after trying this.

Return value order is changes when send HashMap in Ajax Post

I am using Spring as backend and Ajax to Get and Post data. In my controller, I return HashMap. Everything is working fine. But when I receive data in javascript file the data order is changing. What am I doing wrong?
For example when I send
map.put("name","aaa");
map.put("name","bbb");
map.put("name","ccc");
in js file I get different order like ccc,aaa,bbb. Changed order is always same. It is not random.
Here are some code I am using.
Controller
#RequestMapping(value = "/history", method = RequestMethod.GET)
public #ResponseBody Map<String, myModel> getHistory() {
Map<String, ChatModel> userInfo = md.getUserInfo(userId);
return userInfo;
}
Get method
$.ajax({
contentType: "application/json;charset=utf-8",
type : "GET",
url : "../Spring4MVCHelloWord/history/",
dataType : 'json',
success: function(data){
displayHistory(data);
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
Try using a LinkedHashMap instead. A LinkedHashMap will iterate in the order in which the entries were put into the map. If performance is something you desire and you can do away with ordering, then go for a HashMap.

$.AJAX Post not working in JS but works in Advanced Rest Client

I'm having an issue with my JavaScript being able to contact the HttpPost service. I can access the same signature using the "Advance Rest Client Application" for chrome. However when I run my code in Console in Chrome I am unable to reach the service. Any thoughts? What am I missing from the signature on one vs the other? Please let me know if you need any more information.
JS AJAX Request (Stuck in Pending status)
$.ajax({
type: 'POST',
url: 'http://local/r/GetSettings',
data: '[{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]',
dataType: "json",
success: function(data){
alert(data)
},
error : function (error) {
alert("Error: " + error);
console.log("ERROR. not working", error);
}
});
C# Service
[HttpPost]
public ActionResult GetSettings(List<Source> sources)
{
return new ContentResult
{
Content = "{}",
ContentType = "application/json"
};
}
Advanced Rest Client Application (Success in returning {})
http://local/r/GetSettings
Content-Type: application/x-www-form-urlencoded
Payload::: [{"SourceId":7,"DataType":0},{"SourceId":5,"DataType":1}]
Change your URL for ajax request
AppContextRootName: Your application context root
$.ajax({
type : 'POST',
url : '/AppContextRootName/GetSettings',
dataType : 'json'
});
Thanks for the answers. I found out my issue why the Ajax call was not executing. I found out you can execute a AJAX statement while paused in the debugger!!! So don't try! It will execute and return and object but it will show pending in the network. Once you unpause the actual call is executed. You should just use Alert("Hello world") in the success and error and you will see it come back once you unpause.

strange behavior of request methods while ajax request

I have such method in my controller
#Controller
#RequestMapping ("/admin/users")
public class AdminUserController {
..
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public #ResponseBody boolean deleteUser(#PathVariable("id") int id,
HttpServletResponse response) {
..
}
..
}
and this is ajax request
$.ajax({
url: '/admin/users/'+id,
type: 'delete',
success: function(data){
console.log(data);
},
error: function(e){
console.log(e);
}
});
When I send this request, it's fails and I get 405. When I looked at response header I saw this Allow:"GET".
Ok. I change in ajax request 'delete' to 'get' but then I get in response Allow:"DELETE" ..
What it can be?
I think that DELETE actions are not allowed by your server security configurations, and basically the header:
ALLOW: GET
is suggesting you to try a GET request instead, but since you specified
method = RequestMethod.DELETE
Spring in rejecting that GET invocation to the method.
you should change method = RequestMethod.DELETE to method = RequestMethod.GET
and issue an HTTP GET request.
Let me know if this helps.

How to send javascript array to a rest service

I have a javascript array that holds a couple of ids. I want to send it to a rest webservice that I have written. Here is the code that I have for that -
$.ajax({
type : 'GET',
url : 'http://localhost:portNo/GlassdoorWebProject/index/getJobsData/list/',
crossDomain : true,
data : JSON.stringify(allIds),
contentType: "application/json",
success : function(data){
alert("success in call2");
},
error : function(XMLHttpRequest,textStatus, errorThrown) {
alert("error");
}
});
When I execute this code I am getting an alert box that says error. This is how the method in my web service looks like -
#RequestMapping(value = "/getJobsData/list/{ids}", method = RequestMethod.GET)
public List<JobDetails> getJobs(#PathVariable("ids") String jobIds) {
System.out.println("ids"+jobIds);
return jobService.getJobDataForIds(jobIds);
}
When I run the it in a browser with the url in the browser it works. But when I run it through the code it does not work. Any suggestions?
Use this code snippet
#RequestMapping(value = "/getJobsData/list/", method = RequestMethod.GET)
public List<JobDetails> getJobs(#RequestParam("ids") String jobIds) {
System.out.println("ids"+jobIds);
return jobService.getJobDataForIds(jobIds);
}
the main problem is that you are sending the ids as the request parameters, but your are looking the values from the url. So i changed the code of your web service and i think it will solve your problem.

Categories

Resources