Ajax call to Rest service not successfully calling success function in ajax - java

I am having some ajax difficulties (and am newish to ajax, but have done a fair bit of searching) when calling a java rest server that I have written. I have a test html page running within the Rest server (using Jetty) and I use the following call -- which works successfully using a .get:
$('#getRVLakeForm').submit(function(e) {
var handle = $('#insertRVLakeHandle').val();
var lakekey = $('#RVLakeKey').val();
var temp = $('#RVLakeTemp').val();
var speed = $('#RVLakeWindspeed').val();
var degrees = $('#RVLakeWindDegrees').val();;
$.get('${pageContext.request.contextPath}/api/recent/lake/' + handle + "/" + temp + "/" + speed + "/" + degrees + "/" + lakekey, function(data) {
alert(data.lake[0].oid);
$('#RMLakeResponse').text("back");
});
Here is the JSON the Rest server returns:
{"user":[],"lake":[{"oid":"519b9a1a3004f8fa1287502a","type":"Lake","handle":"nightstalker","viewedhandle":"","viewedlaketag":"TXFORK","viewedusername":"","timestamp":1369152026668}]}
This call executes the Rest Api and gets JSON back as expected... When I attempt to call the same Rest Api from HTML/PHP application, running under MAMP -- the ajax call works on the out bound call -- I can debug the Java Rest server and see the call come in, and it executes as designed creating JSON to send out. The problem is that I never get a call to the success function in the ajax call (I am not seeing the error function called either).
urlrecent = "http://localhost:8080/server/api/recent/lake/" + handle + "/" + temp + "/" + speed + "/" + degrees + "/" + lakekey;
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "jsonp",
url: urlrecent,
success: function (data) {
alert("hello there!");
alert(data)
},
error: function () {
alert('failed');
}
});
I have even tried a getJSON instead..no luck. In the mean time I will continue search Stack and the web for something that will work. I have tried a dataType of just "json" as well.
Thanks in advance.
=====
Yes, munged the contentType, but that didn't matter.

Try it in IE8 and set dataType: "html"
urlrecent = "http://localhost:8080/server/api/recent/lake/" + handle + "/" + temp + "/" + speed + "/" + degrees + "/" + lakekey;
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "html",
url: urlrecent,
success: function (data) {
alert("hello there!");
data = JSON.parse(data);
alert(data)
},
error: function () {
alert('failed');
}
});
if you get syntex error at data = JSON.parse(data) or "hello there" in alert , it is encoding problem. In this case you should use response.setCharacterEncoding("UTF8")

Related

Ajax call returns string for Highcharts series but result is wrong (parsing error?)

I'm developing a Java Spring-Hibernate application that uses Highcharts. I've got a JavaScript function that, when called, it makes an Ajax call to get the chart data (series) and creates the chart with it:
<!-- Stacked bar chart -->
<script type="text/javascript">
//Function that plots the highcharts chart
function plot(park) {
$.ajax({
type: "get",
url: "MainView/report/datagaps/" + park,
dataType: "text",
error: function (error) {
console.log(error);
alert('Error while requesting datagaps for ' + park + ' : ' + error);
},
success: function (result) {
$("#chart" + park).highcharts({
chart: {
type: 'column'
},
series: result
});
}
});
}//END_FUNCTION
</script>
I've removed most of the plot options code, so you see the most relevant code above. There is a model method that deals with this request:
#RequestMapping(value = "/datagaps/{parkName}", method = RequestMethod.GET)
public #ResponseBody String datagaps(#PathVariable String parkName, Map model, HttpSession session) {
LOGGER.debug("Successfully called datagaps for '" + parkName + "'");
LOGGER.debug((String) session.getAttribute("chartData"+parkName));
return (String) session.getAttribute("chartData"+parkName);
}//END_METHOD
The method is quite simple: a session string variable is returned, which is the one that should be used in series: result.
The thing is that this generates an unexpected result:
However, if I set a model variable session.setAttribute("chartData" + park, rrdao.getParkData().get(park)); before loading the form and I use it instead of the result like series: ${chartDataAA}, it works:
This is quite weird, since the data used is exactly the same: both ajax call and model variable come from the same place, and they are logged before beign send, which allows me to be sure data is good. This data has a format like [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[1412460000000,0],[1412546400000,0],[1412632800000,0]}]
I bet is some kind of string parsing problem when it is returned from the ajax call, perhaps due to the single quotations, but I don't know how to deal with it.
Please help!
Maybe it is misspelling, but your single serie which you have as missing bracket in data array. It should be: [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[141246‌​0000000,0],[1412546400000,0],[1412632800000,0]] }]
Change: dataType: "text" to dataType: "json"
Then in the controller if you use jackson json just return a List

Ajax call servlet and pass a ArrayList via Gson, display the list on html using javascript

I'm currently studying how to ajax call servlet and pass an ArrayList via Gson, display the list on HTML using javascript
Here is the learning code I got from the internet --- Sample code
I have some questions about it if the response data is a list, how we display it via javascript.
Here is the sample for display a single object response
$.ajax({
type: "POST",
url: "search",
data: {"name":name, "indicator":indicator, "price":price, "location":location},
dataType: "json",
success: function(data,textStatus,jqXHR){
$('#test').show();
if(data.success){
$("#ajaxResponse").html("");
$("#ajaxResponse").append("<div class ='counter' data-countdown=" + data.itemsInfo.time + "></div>");
$("#ajaxResponse").append("<div><img src=" + data.itemsInfo.url + "></div>");
$("#ajaxResponse").append("<div class='description' ><p>Name:" + data.itemsInfo.name + "<br><br> Price:$" + data.itemsInfo.price+ "<br><br>Location" + data.itemsInfo.location
+"Description:" + data.itemsInfo.description + "</p></div></c:forEach>");
}
else {
$("#ajaxResponse").html("<div><b>No result found!!!</b></div>");
}
}
});
Will these data.itemsInfo.size(),data.itemsInfo.get(0).name works here?

REST disregards any part that is not English characters , when receiving UTF-8

Sending ajax request in UTF8 to the server that uses REST , disregards any part that is not English characters
I'm using JAVA with REST on the server side , and the client sends ajax requests in UTF8 , that includes Hebrew words .
The AJAX request :
var clientNumber = '12344432432';
var userID = '321321321';
var someHebrewWord = ...;
var someEnglishWord = ....;
var servletUrl = '/Management/services/manager/' + clientNumber + '/' + userID + '/' + someEnglishWord + '/' someHebrewWord;
alert('Sending this :' + servletUrl);
$.ajax({
url: servletUrl,
type: 'POST',
cache: false,
data: { },
success: function(data){
alert('Return value is:' + data);
window.location = "./replyPage.html";
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err + " " + JSON.stringify(jqXHR));
}
});
On the server side , I use REST :
#Produces({ "application/json" })
#Path("/manager")
public class Management {
#POST
#Path("{clientNumber }/{userID }/{someEnglishWord}/{someHebrewWord}")
#Produces("application/json")
public boolean insert(#PathParam("clientNumber") String clientNumber, #PathParam("userID") String userID,
#PathParam("someEnglishWord") String someEnglishWord, #PathParam("someHebrewWord") String someHebrewWord)
{
// do some stuff
}
#POST
#Path("{clientNumber }/{userID }/{someEnglishWord}")
#Produces("application/json")
public boolean updateSomething(#PathParam("clientNumber") String clientNumber, #PathParam("userID") String userID , #PathParam("someEnglishWord") String someEnglishWord)
{
// do other stuff
}
// more code
}
So , when the AJAX request is sent , the updateSomething() is invoked instead of insert() ,
even though I'm sending 4 fields , and not 3 !
What causes this , and how can I fix it ?
Much appreciated
Allowed characters in a URL is restricted. You have to encode the URL with encodeURIComponent.
A better option might be posting those parameters in a data -variable and using #FormParam instead of #PathParam.

Response Data not passed through json

The following script is suppossed to return for me the requests booked and append the data I got through json to html.
function readUsers() {
//display ajax loader animation
$( '#ajaxLoadAni' ).fadeIn( 'slow' );
$.ajax({
url: 'user_transactions/get_request',
dataType: 'json',
success: function( response ) {
alert(response)
for( var i in response ) {
response[ i ].updateLink = updateUrl + '/' + response[ i ].id;
response[ i ].deleteLink = delUrl + '/' + response[ i ].id;
}
//clear old rows
$( '#records' ).html( '' );
//append new rows
$( '#readTemplate' ).render( response ).appendTo( "#records" );
//hide ajax loader animation here...
$( '#ajaxLoadAni' ).fadeOut( 'slow' );
}
});
} // end readrequest
I am able to get the data from the url but when I alert the response , it is empty , how can I pass the data through the success function?
It looks like you do not have a good response from the server side. First, define the type of you request, so add the type in your ajax request setting type: 'POST' or 'GET'. It would be better if you post here the server side code.

Ajax calling a java Rest API

I am having ajax problems that I cannot figure out, and need some help... I am using Spring for my REST api and my ajax calls don't seem to work... I have searched the forums and haven't been able to find an answer:
My java Spring api is as follows:
#Controller
#RequestMapping("api")
public class RecentRestController {
RecentService recentService;
#Autowired
public void PersonRestController(RecentService recentService) {
this.recentService = recentService;
}
/**
* Add recent lake, then get recently viewed lakes and users ordered by timestamp
* #param handle
* #return
*/
#RequestMapping(value = "recent/weather/{auser}/{temp}/{windspeed}/{winddeg}/{laketag}", method = RequestMethod.GET)
#ResponseBody
public RecentlyViewedList getRecentlyViewedLakes(#PathVariable String auser, #PathVariable Integer temp,
#PathVariable Integer windspeed, #PathVariable Integer winddeg, #PathVariable String laketag) {
RecentlyViewedList rvl = recentService.getRecentlyViewedWeather(auser, temp, windspeed, winddeg, laketag);
return rvl;
}
When I use ajax to call this Java REST from ajax it doesn't seem to work. My ajax call looks as follows from html/php:
new $Ajax.Request('http://localhost:8080/server/api/weahter/lake/' + agruments.auser + '/' + arguments.windspeed +'/' + arguments.winddeg + '/' + arguments.laketag, {
type : "GET",
//:url : recenturl,
//cache : false,
async : false,
crossDomain: true,
dataType : 'jsonp',
//data: arguments,
success : function(recent) {
alert("SUCESS");
var i=0;
var lakecount = recent.lake.length;
var usercount = recent.user.length;
alert("lakecount:" + lakecount);
alert("usercount:" + usercount);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown);
},
});
It never seems to work. It never calls my REST api correct.. What am I doing incorrectly?
Something is wrong with how I calling my REST service..
Any help is greatly appreciated..
Thanks in advance.
As you are checking for a #GET request, the most obvious thing to do is to try to hit the API directly from a browser ( type in your URL field
http://localhost:8080/server/api/weahter/lake/' + agruments.auser + '/' + arguments.windspeed +'/' + arguments.winddeg + '/' + arguments.laketag
with the parameters resolved ).
Other thing you should be checking is that your context path is 'server' as that is where the URL is pointing.
Also you have and spelling error in the first parameter of the URL: 'agruments' instead of 'arguments'
Yeah, the request has recent in it. What I cannot figure out is that if I build it manualy:
url : 'http://localhost:8080/server/api/recent/lake/nightstalker/3/3/3/TXFORK'
it works. But when I build it with variables, it does not.

Categories