Data does not displayed correctly when using tokeninput with liferay portlet? - liferay-6

I am using token input to search data as follows:
<portlet:resourceURL var="categoryRequestURL" />
<script type="text/javascript">
$(document).ready(function () {
var catUrl = "<%=categoryRequestURL%>";
var cat_input_id = "<%=portletNamespace%>categories_selector";
$("#textbox_id").tokenInput(catUrl, {theme: "facebook"});
});
</script>
And in the public void serveResource():
PrintWriter writer = resourceResponse.getWriter();
JSONObject j1 = JSONFactoryUtil.createJSONObject();
j1.put("id", "1");
j1.put("name", "Data center");
JSONObject j2 = JSONFactoryUtil.createJSONObject();
j2.put("id", "2");
j2.put("name", "Database");
catJsonArray.put(j1);
catJsonArray.put(j2);
writer.write(jsonArray.toString().trim());
writer.flush();
writer.close();
The problem was whatever I entered in the input box, all data in the json array was displayed:
However, if I hard coded json data instead of using resource url. Then it worked correctly.
Does any one have any ideas?

I have no experience with liferay in the slightest, but think I can see what is 'theoretically' the problem.
With jquery tokeninput, when you use an external URL to get your search results, you must deal with the search logic yourself. This is to allow you to query databases and such like. The search parameter is (by default) sent to your page in the GET parameter 'q', and the JSON you return should only be the relevant search results, rather than the entire collection of data.
As I say, I have no idea how to implement such a thing using liferay - but from looking at your code, there doesn't seem to be any point where that logic could be in there!

Related

SmartGWT not able to parse data in the DataSource.transformResponse() method

I need some help please...
I am working with a GWT enabled web application. I am using the gwt-2.3.0 SDK.
I have a method that extends the DataSource class and uses the transformResponse method:
public class DeathRecordXmlDS extends DataSource {
protected void transformResponse(DSResponse response, DSRequest request, Object data){
super.transformResponse(response, request, data);
}
}
As I understand, the transformResponse() method should get control and at this point, I will have access to the data that is being provided to the Client side of my application. I am trying to work with the Object data parameter (the third parameter) that is passed in.
I am expecting an XML formatted string to be passed in. The XML will contain data (a count field) that I need to access and use.
I don't seem to be getting an XML string. Here's what I know...
I do see the XML data being passed to my webapp (the client). I can see this because I inspect the webpage that I am working with and I see the Response data. Here's an example of something that I expect to receive:
XML data from Query:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Collection numRecords="0">
<DeathRecords/>
</Collection>
The above XML is valid (I checked it in a Validator). This is a case where there was no data (No Death Records) being returned to my application. The numRecords XML attribute is set to "0". Of course, If I do have records returned the numRecords will contain the number of records and I'll get that same number of DeathRecord nodes.
I am not getting the above data (or, I don't know how to work with it) in the transformResponse() method.
Here's what I've done to try to figure this out...
The Object data parameter... it is a JavaScriptObject. I know this because I did a .getClass().getName() on it:
DeathRecordXmlDS::transformResponse() data.getClass().getName(): com.google.gwt.core.client.JavaScriptObject$
Then, to try to work with it, I converted it to a String:
com.google.gwt.core.client.JavaScriptObject dataJS = (com.google.gwt.core.client.JavaScriptObject)data;
System.out.println("DeathRecordXmlDS::transformResponse() data as a JavaScriptObject: "+dataJS.toString());
The contents of 'data' formatted as a String look like:
DeathRecordXmlDS::transformResponse() data as a JavaScriptObject: [XMLDoc <Collection>]
So, it looks like I have something that has to do with my 'Collection' node, but not a String of XML data that I can parse and get to my numRecords attribute.
What do I need to do to gain access to the XML in the transformResponse() method?
Thanks!
I think your data object is already translated to a javascript collection.
Maybe you could use the utility class XMLTools to retrieve your numRecords information:
Integer numRecords = Integer.parseInt(XMLTools.selectString(data, "Collection/#numRecords"));
After working on this for an additional period of time I was able to read the XML data that I am working with. I used the following piece of code:
try{
JsArray<JavaScriptObject> nodes = ((JavaScriptObject) XMLTools.selectNodes(data, "/Collection/#numRecords")).cast();
for (int i = 0; i < nodes.length(); i++) {
com.google.gwt.dom.client.Element element = (com.google.gwt.dom.client.Element) nodes.get(i);
numRecords = element.getNodeValue();
}
} catch(Exception e){
// If Parsing fails, capture the exception
System.out.println("DeathRecordXmlDS::transformResponse() Not able to parse the XML");
}
I think the first step to solving this was understanding that the parameter 'data' of type Object was really a JavaScriptObject. I learned this after looking at the .getClass() and .getName(). This helped me understand what I was working with:
System.out.println("DeathRecordXmlDS::transformResponse() data.getClass().getName(): "+data.getClass().getName());
Once I knew it was a JavaScriptObject, I was able to do a little more focused of a Google search for what I was trying to accomplish. I was a little surprised that the XMLTools.selectNodes() function worked the way it did, but the end result is that I was able to read the numRecords attribute.
Thanks for the suggestion!

How to create a website with a searchbar to query a mongo database?

I have a large mongoDB database set up and am trying to create a website where a user can use a searchbar to query the database remotely and have the results posted on the site (strictly read-only).
I have experience with databases for data analysis, but have never created a website for querying results.
I'm don't have any experience with web development and don't know what platforms (PHP? node.js?) to use.
Thanks in advance.
There are the following steps to the problem:
Create the front-end, which will consist of HTML, CSS, and Javascript. Beginners often find it easiest to work with jQuery and jQuery UI, because they are well-documented and contain plugins for almost all possible scenarios (they should not, however, be used to create large complex applications!). Bootstrap or Foundation can help you with the HTML / CSS.
Create a (probably) JSON API, which the front-end can communicate with to submit searches and retrieve results. You could use PHP, Python, Ruby, or many other languages to do this. For a simple site like the one you're describing, it's more a matter of preference than anything else.
Translate the search request from the front-end into the MongoDB query APIs, and return the results through the API. You will use a MongoDB client library compatible with whatever language you have chosen.
Depending on your needs, you may be able to eliminate (2) by using an existing REST API for MongoDB.
Note that if you just want to make MongoDB data accessible via searching / charting, then you may be able to avoid coding altogether by leveraging SlamData, an open source project I contribute to. SlamData lets you use Google-style search (or more advanced SQL) to query MongoDB and get the results back in tabular or chart form.
I am doing such in nodejs.
In my server side app I have connection via mognoose like:
var mongoose = require('mongoose');
mongoose.connect('mongodb://yourhost/database');
Next you need to have your model to your database
var YourDBVarName = mongoose.model('collectionName', {
yourfields1 : type,
yourfields2 : type,
yourfields3 : type
...
});
Then I make GET for it
var express = require('express');
var app = express();
app.get('/dblisting', function(req,res){
YourDBVarName.find({ yourfieldsX: 'value'}, function(err, data) {
if(err) {
res.send(err.message);
}
else{
res.send(data);
});
});
Then simply you make some GET with $.ajax to yournodeserver.com/dblisting and in response you recive your collection filtered as in
{ yourfieldsX: 'value'}
Ofcourse you may do just {} so you get all your stored data.
SLee
If you want know about retrieving data from mongoDB, you can use my github https://github.com/parthaindia/CustomMongo .Use getByCondition() method which requires collection name and a Map . The Map can be your queries in form of key value pair,Key being the column name. I use this method when I write search Query for the web development. The java code gives you a Json. Write a Servlet to post your Json to WEB UI.
This is an example to show how to post the retrieved data using Js ,"server_base_url + /server/FetchData" would be your Service URL.The data you has to be appended to a table . Or a span ,depends on what you actually want.The below code appends data
function getdata() {
$.get(server_base_url + "/server/FetchData", {
}).done(function (data) {
$.each(data, function (index, value) {
alert("The Index" + index + "The Value" + value);
$("#11table1").append("<tr><td id='dynamicid1" + index + "'>" + value + "</td></tr>");
});
});
}
This function can be used for defining table
function defineTable() {
$("#mainDivID").text("").append("<div id='contpanel' class='contentpanel'>");
$("#contpanel").append("<div id='rowid11' class='row'>");
$("#rowid11").text("").append("<div id='row11table1' class='col-md-12'>");
$("#row11table1").text("").append('<br /><br /><center><h5 class="lg-title mb5" style="background-color:#428BCA;height:20px;color:#fff;padding-top:4px;"><b>Heading</b></h5></center>');
$("#row11table1").append("<div id='table11id1' class='table-responsive'>");
$("#table11id1").append("<table id='11table1' class='table table table-bordered mb30' >");
$("#11table1").append("<thead><tr><th>Index</th><th>Value</th></tr></thead>");
}

How to inject data from db into jade template?

I am trying to import data from mongodb into jade template, in order to show them in graph. I am using chart.js inline script, in order to render data on graph. So data from Mongodb is on the page, and I can access it like this:
each city in cities
p #{city.name}
And here is how I pass data to page:
exports.index = function(req,res){
var cities = City.find({}).limit(20);
cities.exec(function(err,doc) {
res.render("index",{cities:doc});
});
};
I created same app with php, by simply passing data to page and injecting data into javascript graph(with json_encode)
Here is final result with php:
It was easy, since php data are global to HTML page. How to do that with Jade ?
Thanks
Ah, so your goal is to both use the city data to generate HTML on the server but ALSO make it available in the browser as raw javascript object data. To do that you format it as JSON and stuff it into a <script> tag. There are modules to help with this such as sharify,
but the basic idea in your jade template do something like:
In your express route handler javascript:
exports.index = function(req,res){
var cities = City.find({}).limit(20);
cities.exec(function(err,doc) {
//There are tricky rules about safely embedding JSON within HTML
//see http://stackoverflow.com/a/4180424/266795
var encodedCityData = 'window.cities = ' + JSON.stringify(cities)
.replace(/</g, '\\u003c')
.replace(/-->/g, '--\\>');
res.render("index",{cities:doc, encodedCityData: encodedCityData});
});
};
In your jade template:
script!= encodedCityData
In the browser, you will have access to the data via the cities variable which has been set onto the window object.

from javascript to jinja2

Is it possible to access data obtained via .getJSON call in jquery as a jinja2 variable ?
$.getJSON(
$SCRIPT_ROOT +"/gitem/"+node.id,
function(data){
if (data.length > 0){
$.each(data, function(index,val_dict) {
var button_id = "button_"+String(index);
var popup_id = "element_to_pop_up_"+String(index);
var append_string = sprintf('<div class="icony"><img src="%s" height="75" id="%s" >%s</div>',val_dict.img_url,button_id,val_dict.img_caption);
var bpopup_element = sprintf('<div id="%s"><a class="bClose"><img src="%s" width="500px">X<a/></div>',popup_id,val_dict.img_url)
$('.data_area').append(append_string+bpopup_element);
$('#'+popup_id).hide();
$('#'+button_id).bind('click', function(e) {
e.preventDefault();
$('#'+popup_id).bPopup();
});
});
}
else
{
var append_string = '<div class="icony">No Images to display for this category</div>';
$('.data_area').append(append_string);
}
$("#list_viewer").css("display", "block");
});
For example in the above I am getting the data and then constructing the DOM within js. While what would be best would be to import data via .getJSON and then set the data as a jinja2 variable.
Later I can use that variable within jinja2 template ?
it that possible ?
or better still...
can a jinja macro be called from within the .getJSON function ? that can also allow embedding of json data within jinja2....
thanks for any pointer...
Probably not. Jinja generally runs on the server, rendering your web site templates before sending them off to the client. The client (i.e. your web browser) will not have access to the templates.
If you'd like to use Jinja templates to render client-side JSON objects, you could take a look at Jasinja, which is a tool to convert your Jinja templates to JavaScript, which you can then use in the browser. A number of similar tools exist.
Finally, another solution is to send your JSON data to the web server, render them to HTML via Jinja, then send back the resulting HTML in the XMLHttpRequest response. However, if you've obtained this JSON data from the same server you use to render templates, you might be better off just having HTML sent to the client directly and added to the DOM from there.

MVC jquery ajax form server side validations

We have a number of forms on our site that are shown with jquery .dialog and we submit them using an ajax post request.
I've done a fair bit of research and from what I can tell there isn't any definite patterns on how to return validation errors from the server side as a result of an ajax request.
Pretty much the only pattern I could find was to post the form and then do validation server side and in either case return a json object that encapsulated a result and if the result was incorrect the form html
ie.
{result: true}
{success: false, html = "<form>....</form>"}
So in the case the result was false you would need to rewire up any events attached to items on the form as you would be replacing the old form with the new form that has the validation errors.
This seems like an ok approach but you also end up potentially returning a lot more data to the client that you need to when they only really need to validation messages and you are also forced to rewire the form up which is a bit annoying.
I did find one other mention of somehow getting the validation errors and returning them in a json object from the action and somehow telling the client to display them against the correct fields.
Is there any frameworks out there that make this easier or should I write my own or just stick to returning the entire partial for the form and rewiring it when validation is incorrect?
I don't know of any frameworks that handle this particular case–and I don't know that there's a clear best practice–but it's easy enough to serialize validation errors and return them as a JSON object. You could try this extension method on ModelStateDictionary:
public static IEnumerable<ValidationResult> GetValidationResults(this ModelStateDictionary dictionary)
{
foreach (var key in dictionary.Keys)
foreach (var error in dictionary[key].Errors)
if (error != null)
yield return new ValidationResult(error.ErrorMessage, new string[] { key });
}
And in the controller:
if (!ModelState.IsValid)
{
return new JsonResult(ModelState.GetValidationResults());
}
But you're right, you would then have to loop through the object and append the errors to the correct fields. If you have ClientValidationEnabled and UnobtrusiveJavaScriptEnabled set to true, the loop would look something like this:
$.each(errors, function(i, item) {
$('span[data-valmsg-for=' + item.MemberNames[0] + ']').html(item.ErrorMessage);
})
If not, it wouldn't be that difficult to match up the error messages to their respective fields as the object contains the field name. This would definitely save you some data across the wire, but it moves a larger share of the validation responsibility into Javascript. Like I said, I don't know that there's a clear best practice, but I have used this method in the past with success.