How to send javascript array to a rest service - javascript

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.

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.

Changing pages spring boot application

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.

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.

xml parsing error syntax error line number 1 column 1 in jquery ajax

Following is the code I use for an ajax call. While executing this it gives me an error xml parsing error syntax error line number 1 column 1 in fiebug. I viewed some questions stating the same problem and they suggested that there was some syntactical problem. I checked again but couldn't find out the real culprit. Please tell me what I am doing wrong.
$.ajax({type: "GET",
cache: false,
url: 'url',
data : 'param1='+ param1val+ '&param2='+param1val,
dataType: 'json',
success: function(Obj){
if(Some Condition){
//Some Code
}else{
//else code
}
},
});
Here goes some controller code.
#RequestMapping(value = "url", method = RequestMethod.GET)
public #ResponseBody SomeObject url(#RequestParam(value="param1val") String abc ,#RequestParam(value="param2val") String xyz)
{ //some code}
Edit
I added some debugging code to JS and the controller code as well. To my surprise, control executes successful first comes (in JS) and then goes into controller. Is it supposed to happen like this?
Firefox shows this error if the response type is not set correctly. It tries to parse the response as XML. To fix it, set the response type for what you are sending back to the client, for example for JSON with Spring:
#RequestMapping(value = "url",
method = RequestMethod.GET,
produces = "application/json")

Accessing MVC Action from another application via javascript

I have an MVC 3 web app that has an Action which I need to access from a webform app via javascript.
My action returns a Json result, which I have checked works just fine. However, when accessing it with javascript from another application, I can see it reaching my action, doing all the work, returning my data, but the jquery function then gives me an error 200 and no data.
Example:
My MVC Action:
public ActionResult GetData(int categoryId)
{
var listofSeries = new List<string>
{
"foo1",
"foo2",
"foo3"
};
return Json(listofSeries, JsonRequestBehavior.AllowGet);
}
This returns me: ["foo1","foo2","foo3"]
Normally, my javascript function is used to query a database and get data back for a Highcharts chart but I have the same issue with this kind of example.
<script type="text/javascript">
$(document).ready(function () {
var foo = getData(9);
});
function getData(categoryId) {
var results;
$.ajax({
type: 'POST',
url: 'http://localhost:xxxx/Home/GetData',
//contentType: "application/json; charset=utf-8;",
async: false,
data: { "categoryId": categoryId },
dataType: "json",
success: function (data) {
console.log("results: " + data);
results = data;
}
});
return results;
}
</script>
With this I get:
http://localhost:63418/Home/GetData?categoryId=9 200 OK
results: null
If I add the contentType, I can't even see the function running in the firebug console, all I see is results: null. When I remove it I do but I get the error above.
I've been told it might not be doable because of "Cross-site scripting". And to instead have my javascript function call a webservice (or handler but I haven't quite figured out how to make one of those yet) that will then call my action, return my data to the service who then returns the data to the javascript.
But now I'm getting a 415 Unsupported Media Type error message when trying to connect to my webservice.
My IWebService.cs:
[ServiceContract]
public interface IWebService
{
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, Method = "POST")]
void GetData(int mileId);
}
My WebService.svc:
public void GetData(int categoryId)
{
string url = "http://localhost:63418/Home/GetWoWData?categoryId=" + categoryId;
WebRequest wr = WebRequest.Create(url);
WebResponse response = wr.GetResponse();
}
I'm not returning anything yet, it won't even go in this function. Giving me the 415 error message.
If I change the contentType to "text/xml" I get an error 400.
I would really like to have this work without using the webservice, and figure why I get an error 200 OK when I can see the action running, but if that's not possible, any idea why the webservice isn't working?
Thanks.
string url = "http://localhost:63418/Home/GetWoWData?categoryId=" + categoryId;
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultNetworkCredentials; // uses current windows user
var response = (HttpWebResponse)wr.GetResponse();
I only just remembered I had this post and found the solution a while ago. It was solved by adding the credentials (in my case the current windows user) and getting the response as an HttpWebResponse.
200 makes me think everything is working ok, but IE is using a cached result, i've run into this problem before with IE. try adding:
$.ajaxSetup({
// Disable caching of AJAX responses */
cache: false
});
this will make it append a random parameter, and will stop IE from being stupid.

Categories

Resources