After browsing thru SO, i found this piece of code everywhere, even I want to implement AutoComplete, I am using Solr to implement search, and wanted to use TermsComponent foe implementing Autocomplet
var cache = {};
$("#textbox").autocomplete({
source: function(request, response) {
if (request.term in cache) {
response($.map(cache[request.term].d, function(item) {
return { value: item.value, id: item.id }
}))
return;
}
$.ajax({
url: "/Services/AutoCompleteService.asmx/GetEmployees", /* I use a web service */
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
cache[request.term] = data;
response($.map(data.d, function(item) {
return {
value: item.value,
id: item.id
}
}))
},
error: HandleAjaxError // custom method
});
},
minLength: 3,
select: function(event, ui) {
if (ui.item) {
formatAutoComplete(ui.item); // custom method
}
}
});
Now my question is, How to configure the url source, wat it should be, the following url
http://localhost:8983/solr/terms?terms.fl=name&terms.prefix=at&wt=json&omitHeader=true
gives me perfect result, now pls tell me wat should be my url source, and if i want to customize add more parameters like terms.lower=py&terms.lower.incl=false&indent=true&wt=json etc ,should i better harcode them in url or in my java class like
List terms = query(q, Integer.parseInt(limit));
private List<TermsResponse.Term> query(String q, int limit) {
List<TermsResponse.Term> items = null;
SolrQuery query = new SolrQuery();
query.addTermsField("spell");
query.setTerms(true);
query.setTermsLimit(limit);
query.setTermsLower(q);
query.setTermsPrefix(q);
query.setQueryType("/terms");
try {
QueryResponse qr = server.query(query);
TermsResponse resp = qr.getTermsResponse();
items = resp.getTerms("name");
} catch (SolrServerException e) {
items = null;
}
return items;
}
Please help, um not so good in jquery, so wanted to confirm one more thing,for wat i need, i just need to modify the url over here or have to customize few more things
It's not very likely that you need to parameterize this client-side, so set those parameters server-side. Setting them with code instead of hardcoding them in the URL is generally better, it reveals the intention. Also remember that you can set parameters in the solr config.
Lastly, don't program by coincidence. Understand the jQuery snippet you're using, otherwise you will have problems sooner or later.
Related
I have 3 Drop Down list which are dependent on each other as Specific country contain Certain States and those states contain specific City,
all These Country, state and City have a Service call to DAO to get data from DB how i can manage Drop Down with the Help of Spring MVC to display proper Country and state and city in Drop down List of each
Create a REST Call to produce JSON Country object has a list of State Objects
#RequestMapping(value= "/countryState", produces = MediaType.APPLICATION_JSON_VALUE)
public List< CountryStateCity> retrieveCountryState() {
return ddlService.retrieveCountryState();
}
Create another Rest call to get the City base on Country and State
#RequestMapping(value= "/city", produces = MediaType.APPLICATION_JSON_VALUE)
public List< CountryStateCity> retrieveCity(String country,String state) {
return ddlService.retrievecity(country,state);
}
I used AJAX/jquery in this example To
//Fill first Dropdown
$.ajax({
type: "GET",
url: "http://192.168.33.60:8080/countryStateCity?callback=?",
dataType: "jsonp",
jsonpCallback: 'jsonCallback',
cache:false,
success: function(data) {
var dataToStore = JSON.stringify(data);
localStorage.setItem('jsonResults', dataToStore);//Store json to browser local storage
$("#country").get(0).options.length = 0;
$("#country").get(0).options[0] = new Option("Select Country", "0");
$.each(data, function(index, item) {
$("#country").get(0).options[$("#country").get(0).options.length] = new Option(item.mfrname, item.countryId);
});
},
error: function(e) {
// alert("Error Loading Manufactures");
}
});
$("#country").on("change", function (event) { //Change event on country Drop down clear State and City Dropdowns
var countryId=$("#country").val();
var stateId=$("#state").val();
$('#City').find('option').remove().end(); //clear City dropdown and add only select
$("#City").get(0).options[0] = new Option("--Select--", "0");
$('#state').find('option').remove().end();
$('#category').find('option').remove().end();
resetTables();
var localData = JSON.parse(localStorage.getItem('jsonResults'));// Go to local storage and get state values
var i = null;
for (i = 0; localData.length > i; i += 1) {
if (localData[i].countryId === countryId) {
$.each(localData[i].states, function(index, value) {
$("#state").get(0).options[$("#state").get(0).options.length] = new Option(value.description, value.code);
});
}
}
});
$("#state").on("change", function (event) {//State change event clear city then go to
var countryId=$("#country").val();
var stateId=$("#state").val();
// alert(countryId!="0"&&stateId!="0");
$('#City').find('option').remove().end();
$("#City").get(0).options[0] = new Option("--Select--", "0");
$('#category').find('option').remove().end();
resetTables();
if(countryId!="0"&&stateId!="0"){
//now call the citys Rest call
$.ajax({
type: "GET",
url: "http://192.168.33.60:8080/cities?countryId="+countryId+"&stateId="+stateId+"&callback=?",
dataType: "jsonp",
jsonpCallback: 'jsonCallback',
cache:false,
success: function(data) {
jsonResults=data;
$.each(data, function(index, item) {
$("#City").get(0).options[$("#City").get(0).options.length] = new Option(item.description, item.code);
});
},
error: function(e) {
// alert("Error Loading cities");
}
});
} else{
$("#City").get(0).options[0] = new Option("--Select--"+countryId, "0");
}
I made this from existing code and have not tried it but you should get the gist
At first, you should get familiar with MVC concept.
The data you get from service by controller will act as the M. And the data will be passed to the view(V). Then you can use the data and creat a V. Normally, the View is created by using HTML and JSP. In your case, you can use JSP or any other template frameworks to creat three dropdown lists using the data.
I know the badRequest() in play framework may result in rerendering a page like,
badRequest(views.html.admin()),
but I would like to return a String, in my case a SQLException.
(SQLException e)
If I return ok(e.toString()) instead of return badRequest(e.toString())it works, I think the return type of badRequest may be the problem. If I alert the data I get from the ajax call, I get for bad request [Object][object].
Is it even possible to return a String at badRequest() in java play framework?
My Javascript code is this :)
$("#deleteBuildingConfirm").click(function(q){
$('#confirmDelete').modal('hide');
$.ajax({
type : 'POST',
url : '#routes.Admin.deleteBuilding()',
data : {
id: idOfBuild, name: nameOfBuild
},
success : function(data) {
alert(data);
/** Wenn ein gebäude.. */
},
error : function(err) {
alert(err);
}
});
return true;
});
at alert(err) I always end up getting [Object][Object], when I trigger an SQLException.
This is my Java function:
public static Result deleteBuilding(){
final Map<String, String[]> values = request().body().asFormUrlEncoded();
final Long idToDelete = Long.parseLong(values.get("id")[0]);
final String nameToDelete = values.get("name")[0];
String message="Deleted on server, row with id: "+idToDelete+"\n "
+"Building with name: "
+nameToDelete+" has been deleted.";
try {
Building.delete(idToDelete);
return ok(message);
} catch (SQLException e) {
// TODO Auto-generated catch block
final String badMessage = e.toString();
return badRequest(badMessage);
}
}
Thanks in advance :), this is really bothering me!
Appreciate your help!
There is no problem with badRequest("Some String") you can use it to return a string, or even any object accepted by Ok().
I think that the bad part lays on your Javascript code that trigger the ajax call, can you post it here it'll be useful.
When jQuery calls the erro call back he gives it an object with all the info needed to handle the error that hapened, if you're interested in the content of the request just change the code to look like this:
$("#deleteBuildingConfirm").click(function(q){
$('#confirmDelete').modal('hide');
$.ajax({
type : 'POST',
url : '#routes.Admin.deleteBuilding()',
data : {
id: idOfBuild, name: nameOfBuild
},
success : function(data) {
alert(data);
/** Wenn ein gebäude.. */
},
error : function(err) {
// use err.responseText instead of err
alert(err.responseText);
}
});
return true;
});
I am using Jquerys Ajax method to talk to my web service. The code seems OK, but I just monitored HTTP traffic using HTTPFox firefox plugin and I noticed unexpected results. To begin with, I am setting the ContentType as application/json and my web service is also producing JSON data but HTTPFox indicates Content Type for my HTTP requests as application/vnd.sun.wadl+xml (NS_ERROR_DOM_BAD_URI).
The Request Method is GET as set in my Ajax request, but HTTPFox indicates my Request method as OPTIONS. And while the Request succeeds and data is returned, the onSuccess method of my Ajax request is not called. Instead, the onError method is called. HTTP Fox is able to capture the data from my web service as response. See the image for HTTP Fox.
Finally, all other request from other processes in my browser seem OK but my HTTP requests are flagged 'RED' by HTTP Fox. The request from other pages and processes seem OK.( GREEN or WHITE).
I have attached screenshot of HTTPFox highlighted on one of my Request. The flagged ones are also from my application.
Image:
I have also pasted the Ajax code I am using to make the HTTP Requests.
window.onload = function() {
var seq_no = getParameterByName("seq_no");
var mileage = getParameterByName("mileage");
document.getElementById("seq_no").value = seq_no;
document.getElementById("mileage").value = mileage;
var param = 'vehReg='+encodeURIComponent(document.getElementById('vehReg').value);
// alert(param);
loadVehicleInfo(param);
};
function loadVehicleInfo(params) {
$("#message").html('<p><font color="green">Loading...</font></p>');
$.ajax({
type: "GET",
url: "http://localhost:8080/stockcloud/rest/vehicles/info",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function(data,status) {
$("#message").empty();
$("#message").html('<p>'+getAsUriParameters(data)+'</p>');
},
error :
function(XMLHttpRequest, textStatus, errorThrown) {
$("#message").html("<p> <font color='red'>The following error occurred: " +textStatus+ ': '+errorThrown+ "</font>");
}
});
};
function getAsUriParameters (data) {
return Object.keys(data).map(function (k) {
if (_.isArray(data[k])) {
var keyE = encodeURIComponent(k + '[]');
return data[k].map(function (subData) {
return keyE + '=' + encodeURIComponent(subData);
}).join('&');
} else {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
}
}).join('&');
};
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Server side Code for the request:
#Path("/vehicles")
public class VehiclesService {
#GET
#Path("info")
#Produces("application/json")
public Response getVehicleInfo(#DefaultValue("__DEFAULT__") #QueryParam("vehReg") String vehReg) {
// Send SOAP Message to SOAP Server
ServerResponse resp = new ServerResponse();
if("__DEFAULT__".equals(vehReg)) {
resp.setError("Vehicle registration must be supplied as a query parameter: ?vehReg=<THE REG NO>");
resp.setResult(false);
Response.status(Response.Status.BAD_REQUEST).entity(resp).build();
}
try {
// actual code to return the car info and return XML string with the info.
connection.disconnect();
String xml = URLDecoder.decode(s.toString(),"UTF-8");
xml = xml.replace("<", "<").replace(">", ">").replace("<?xml version='1.0' standalone='yes' ?>", "");
System.out.println(xml);
resp.setVehicle(new VehicleParse().parse(xml));
resp.setResult(true);
} catch(Exception e) {
resp.setResult(false);
resp.setError(e.getMessage());
e.printStackTrace();
Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(resp).build();
}
return Response.status(Response.Status.OK).entity(resp).build();
}
}
Is there something I am not doing right?
Thanks.
I'm trying to send a json String from an ajax call to a jersey web service. I've looked at many related questions and articles but I haven't been able to get anything to work. When I watch my calls from fiddler I can see the json in the body but when the method is hit the String is blank. Thanks for any help.
getFile: function() {
var urlXls = 'http://localhost:8080/KodiakWebS/Kodiak/KodiakXls/generateXls';
//var json = '{"xls":[{"name":"Pokemon","row":[{"data":"Lugia"},{"data":"Charzard"}]},{"name":"Types","row":[{"data":"Special"},{"data":"Fire"}]}]}'; //encodeURI();
var json = this.get('tempJSON');
urlXls = urlXls.replace(/\s/g, "");
$.ajax({
url: urlXls,
type: "POST",
data: json,
contentType: 'application/json; charset=utf-8', // ;charset=utf-8',
success: function(json, status)
window.location.assign(json.url);
alert("yay");
},
error: function(xhr, err) {
debugger;
alert(xhr+ " || " + err);
}
});
},
#POST
#Path("/generateXls")
#Consumes("application/json")
#Produces({ "application/xls" })
public Response sendWorkBook(final String json) throws Exception {
createWorkbook(json);
FileOutputStream sprdSht = new FileOutputStream("WorkBook.xls");
wb.write(sprdSht);
sprdSht.close();
System.out.println("all done");
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream outPut)
throws IOException,
WebApplicationException {
try {
wb.write(outPut);
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
return Response.ok(stream).header("content-disposition", "attachment; filename = egisDoc.xls").build();
}
If you say you consume application/json, then I think you need to provide a Java object to model the JSON you are supplying.
If you do just want the JSON as a String, then you need to consume text/plain.
I typically have this when I use JAXRS:
#PUT
#Path("entities")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public SomeDomainObject updateSomeEntity(SomeDomainObject someDomainObject) {
// Whatever...
}
Where "SomeDomainObject" is just a POJO with getters and setters.
I normally use the JacksonJsonProvider implementation rather than the JAXB one, and the above style of controller works just fine with JSON marshalling for me. I don't even need to add any JSON annotations to the domain objects either.
I was able to get it working thanks to the suggestions from caprica and tinkering around a little bit. Not much changed in my code but here it is.
#PUT
#Path("/generateXls")
#Consumes("text/plain")
#Produces({ "application/xls" })
public Response sendWorkBook(String json) throws Exception {
System.out.println("json: " + json);
createWorkbook(json);
getFile: function() {
var urlXls = 'http://localhost:8080/KodiakWebS/Kodiak/KodiakXls/generateXls';
//var json = '{"xls":[{"name":"Pokemon","row":[{"data":"Lugia"},{"data":"Charzard"}]},{"name":"Types","row":[{"data":"Special"},{"data":"Fire"}]}]}'; //encodeURI();
var json = this.get('tempJSON');
urlXls = urlXls.replace(/\s/g, "");
$.ajax({
type: "PUT",
url: urlXls,
data: json,
contentType: 'text/plain; charset=utf-8', // ;charset=utf-8',
success: function(json, status) {
window.location.href = json.url;
//window.location.assign(json.url);
//alert("yay");
},
error: function(xhr, err) {
debugger;
alert(xhr+ " || " + err);
}
});
},
now on to trying to download xls file my service creates, hopefully I won't need to ask how to get what I have working (but if anyone has a method they're proud of and would like to share you're more than welcome too).
Thanks for the help.
i have a jquery cod with me and i want to port it to java. Is there any options available to do this task quickly since i am not familiar with java
Here is my code
ASDR.PostStore = function(ec, options) {
this.ec = ec;
this.target = options && options.target;
var self = this;
var _send = function(url, transaction, pre, post) {
$(transaction).trigger(pre);
$(self).trigger(pre, transaction);
$(self).trigger('sending', transaction);
$.ajax({
type : "POST",
url : url,
data : transaction.toString(),
dataType: "json",
success : function(data) {
ec.expand(data, true);//Always updateOnIntern
$(self).trigger('sent', data);
$(self).trigger(post, data);
$(transaction).trigger(post, data);
},
error : function(data){
console.log("Logging error", data);
}
});
};
this.get = function(transaction) {
var url = (this.target + "get");
_send(url, transaction, 'getting', 'gotten');
}
this.persist = function(transaction) {
var url = (this.target + "persist");
_send(url, transaction, 'persisting', 'persisted');
}
/**
* Always asynchronous.
*/
this.is_async = function(){
return true;
}
}
}
Thanks in advance
Renjith Raj
jQuery is Javascript, which is usually executed on the client side. Java is a program language which is executed on the server side. You cannot directly convert jQuery to Java.
You can however use a library such as GWT which translates Java to Javascript. There is also the possibility to statically render content server side. If you search for JSP/JSTL you'll find many resources.