I am new to jQuery and am trying to use the autocomplete widget with an ajax call to my database.
I am able to call the database, returned ArrayList of string values, and converted the response as a JSON object using org.codehaus.jackson.map.ObjectMapper (Do I need to use something else?).
When I put an altar, I can see results as pure strings with comma delimiter, but am not able to see a suggestion list with autocomplete.
Java code that returns the JSON object using org.codehaus.jackson.map.ObjectMapper:
response.setContentType("application/json");
response.setHeader("cache-control", "no-cache");
ArrayList polNo = doa.getPolicyData(ajaxForm.getPolicyNumber());
ObjectMapper mapper = new ObjectMapper();
OutputStream out = response.getOutputStream();
mapper.writeValue(out, polNo);
JavaScript code:
$( "#policyNumber" ).autocomplete({
source: function (request,response){
$.ajax({
type: "POST",
url: "/NB/AjaxSubmit.do",
dataType: "json",
data: {policyNumber: request.term},
success: function (data) {
alert(data);
}
});
},minLength: 3
});
alert data showing as : TMA412732,TMA412733,TMA412734
In above code, I have returned ArrayList of string values and was able to show in autopopulate. I have enhanced the above code to return list of person objects that has first name, last name etc. Now when user typing the firname or last name in the autopopulate , I would like to suggest First name, LastName Middle.
Could someone help to enhance this? Thanks!
success: function(data) {
response(data);//u forgot to set data on response
}
Change success function like
success: function (data) {
response(data); //u forgot to set data on response
}
Related
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],[1412460000000,0],[1412546400000,0],[1412632800000,0]] }]
Change: dataType: "text" to dataType: "json"
Then in the controller if you use jackson json just return a List
I have this javascript code :
$.ajax({
url: 'assignRenameRuleToAgency.do',
data: {agenciesId:agenciesId,ruleId: JSON.stringify ( ruleIDd ) },
success: function(response) {
toastr.success(response.message);
}
})
in the server side I did this :
String ruleId = request.getParameter("ruleId");
String[] agenciesId = request.getParameterValues("agenciesId");
ruleId was correct, but agenciesId was null.
Get JSON response from ajax call and then convert that json response to Java objects using below solutions.
Click here to know the working examples
It is a single String, not an array! You can change your structure to
agenciesId: [agenciesId]
then it will be an array.
I would however map the JSON message to a single POJO, for example by using Jackson.
If the parameter for ruleId can be received the way you describe the following should work:
String ruleId = request.getParameter("ruleId");
String agenciesId = request.getParameter("agenciesId");
I found the solution :
String[] myJsonData = request.getParameterValues("json[]");
I have returned the object array from scriptlet,
<%
List list = new BaseHibernateDAO().executeSQLQuery(queryString);
Object[] data = (Object[]) list.get(0);
out.print(data);
%>
When i tried to get values in jquery it is not showing,
$.ajax({
url: URL,
success: function(data) {
alert(data);
}
});
it is showing as => [Ljava.lang.Object;#22649e15
default toString return classname +# + hashcode.. You have to override toString method. refer this SO link..
A clean approach would be to use some JSON marshaller to convert your Java objects to JSON format. In Javascript you can easily process JSON as it is natively supported.
In Java EE 7 you can use the build-in JSON libraries (in earlier versions you can use e.g. Jackson):
JsonObject value = Json.createObjectBuilder()
.add("field1", "1")
.add("field2", "2")
.build();
JsonWriter writer = Json.createWriter(out);
writer.writeObject(value);
I'm trying to send an array from my jsp to my Servlet via ajax POST request. My array has a few objects with many fields. If I try to send and array with 11 objects - using JSON.stringify - it works OK (the array is received on server-side), but the problem happens when I try to send an array with 12+ objects. The error is: 400 Bad Request and looking with Google Chrome Debugger, I can find this error: fluxos:(unable to decode value) where fluxos is the name of my array.
RELEVANTE PART OF CODE:
for(var i=0; i<numberOfConnections; i++) {
fluxo = criaEstruturaFluxo(i);
fluxos.push(fluxo);
}
$.ajax({
type: "POST",
url: 'Servlet?fluxos='+JSON.stringify(fluxos),
success: function (data) {
alert('success');
}
});
...
function criaEstruturaFluxo(i) {
...
...
var fluxo = {
xOrigem: xOrigem,
yOrigem: yOrigem,
xDestino: xDestino,
yDestino: yDestino,
codWorkflow: codWorkflow,
acaoAvanco: acaoAvanco,
codAtividadeOrigem: codAtividadeOrigem[1],
codAtividadeDestino: codAtividadeDestino[1],
numero: numero,
nomeAtividadeOrigem: nomeAtividadeOrigem,
nomeAtividadeDestino: nomeAtividadeDestino,
codConexao: codConexao,
tipoOrigem: tipoOrigem,
tipoDestino: tipoDestino,
xFluxoOrigem: xFluxoOrigem,
yFluxoOrigem: yFluxoOrigem,
xFluxoDestino: xFluxoDestino,
yFluxoDestino: yFluxoDestino,
deletarArquivo: deletarArquivo,
ultimaConexao: ultimaConexao,
caminhoArquivo: caminhoArquivo,
xTela: xTela,
yTela: yTela
};
return fluxo;
}
My encoded array has 8000+ characters length and because of that, I think it's exceeding the max length a POST request can handle... Is that possible or might be something on the code that I'm sending to my Servlet?
Your url is very long. In theory that shouldn't cause any problems, but there's a practical limit that depends on the server and proxies that you use. Send the data on the body of the request and not on the url.
Agree with Andres & Luiggi. Here's what your modified code would look like:
$.ajax({
url: "Servlet",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "fluxos": fluxos }),
success: function(data) {
alert("success");
}
});
I have an input:
Now this is one input from a div with several different inputs, there is a button called add exp which generates a new div with those inputs by calling href="#" and then jquery does the rest, only the name changes to for example institutionName0, institutionName1 etc so the fields get distinct. In my servlet I want to be able to get the actual input name like institutionName0 so I can check how much of the same fields are generated and that I can put in different values in those different fields.
You can send your form values to Servlet as a jSon object using ajax.
//Example
function onSubmit(divName){
document.forms["formName"]["formName_currentAction"].value = divName;
var theForm = $("form[name=formName]");
var params = theForm.serialize();
$.ajax({
type:"POST",
url:actionURL,
cache: false,
data:params,
success:function(data, textStatus, XMLHttpRequest){
//do something here
},
error:function(XMLHttpRequest, textStatus, errorThrown){
}
});