how to extract array from java to ajax - java

I get the values from database to time array as follow
int[] time=Manager.playTime() ;
responsedata.put("status", "success");
responsedata.put("play", time);
And i am sending this time array to ajax in javascript file as follow
success:function(response){
$('body').css('cursor', 'default');
if(response.status == 'success'){
for( var i=0;i<response.play.length;i++){
alert("playtime---"+response.play[i]);
}
but here i am not getting the values from array .Please help me
Thanks

You responsedata seems to be a Java Map.
Try to use this in your success function
success:function(response){
$('body').css('cursor', 'default');
if(response.status == 'success'){
$.each(response.play, function (value) {
alert("playtime---"+value);
});
}
}

In your ajax you are getting whole object in response i.e. response.
You can get your play object by response i.e. response.play.
now iterate the the values from play object.
for (var i = 0; i < response.play.length; i++) {
//iterate your values here
alert(response.play[i].object_key);
//object_key is temparary name of your play object so give a proper key here.
}

Related

Processing: how to check if JSON Objects are bound

Since the Processing forum is down I hope one of you guys can help me out.
I made a Processing sketch that pulls data from an API (test here: http://www.europeana.eu/portal/api/console.html ) in JSON-format and reads some fields of this data for visualization. Everything works fine so far except when there are fields that are not bound to every JSONObject.
This is the code for the retrieval of the data:
JSONObject json;
json = loadJSONObject("data.json"); // loading my JSON file into the object
JSONArray CHOData = json.getJSONArray("items"); // array of the items I want data from
for (int i = 0; i < CHOData.size(); i++) {
JSONObject CHO = CHOData.getJSONObject(i); // get a specific item
JSONArray previewObj = CHO.getJSONArray("edmPreview"); // this field is an array, so I need to store it in a JSONArray object first
String[] previewArray = previewObj.getStringArray(); // here I store it in my actual string array
String preview = previewArray[0]; // I only need the first element
}
As you can see, I want the first string of the "edmPreview" array in the object. When I run the sketch, I get an error: "JSONObject["edmPreview"] not found."
This is of course because not every item has such an object. But how can I test if there is an object with this name in an item? I tried with if(CHO.getJSONObject("edmPreview") != null), but same error. Is there a way to look into the JSONObject and check the data values for something called "edmPreview"? There is no such function explained in the Processing reference.
The JSON file essentially looks as follows:
{
"items": [
{
"id": "someID",
"edmPreview": [
"http://europeanastatic.eu/api/image?uri=someimage.jpg"
],
// some other fields
}, // some other items
]
}
I'm new to this JSON-stuff, so maybe I miss something important... Thanks for the help!
So I found the answer myself, but not in the Processing reference, but in the actual reference for the JSONObject class in Java (http://www.json.org/javadoc/org/json/JSONObject.html). I tried some of the methods there and found that hasKey() (which is actually something I came up with myself, combining the method "has()" with the term "key", pure coincidence) as a boolean value works very well:
String preview = "";
if (CHO.hasKey("edmPreview")) {
JSONArray previewObj = CHO.getJSONArray("edmPreview");
String[] previewArray = previewObj.getStringArray();
preview = previewArray[0];
}
So now I learned that Processing is essentially just Java and sometimes not every method is written in the Reference. :-)

Passing javascript array to servlet

I have looked previous questions on this topic on SO, but my problem is not solved yet.
I am passing the array from javascript to servlet.
JavaScript Code:
var action = new Array();
function getProtAcionValues(rowNo,columnCount)
{
for(var j=0;j<columnCount;j++)
{
action[j] = document.getElementById('textActions'+rowNo+''+j).value;
alert(action[j]);
}
}
Servlet Code:
String actions[] = request.getParameterValues("action[]");
if(actions!=null)
for(int i=0;i<actions.length;i++)
{
System.out.print(" Action: "+actions);
}
else
System.out.println("Action is null");
Using above code I am getting message "Action is null".
And if I try
String actions[] = request.getParameterNames("action[]");
I am getting Syntax error:
The method getParameterNames() in the type ServletRequest is not applicable for the arguments (String)
Please let me know if there is something wrong in code.
you can just simply get the array with the name of the array...
String actions[] = request.getParameterValues("action");
You can't pass a java array as a parameter, as it is an structure. The best way is to serialize it into an string object like a jSon. You can use JSON.stringify. Simple and efficient. As you can serialize in the server also, it's very useful.
Pass Javascript array variable with form action to send values to servlet, and then use
String[] darray=request.getParameterValues("variable name used with link");

Implementing a news feed system in Java EE and jquery

I am going to implement a news feed notification system where I will show new items on my webpage. Like this: http://jsfiddle.net/8ND53/.
I will be calling a Servlet say every 5 seconds to get updates and the servlet will return items in json format. That seems very simple, but how do I manage that all on the server side?
What I think is:
I have to keep track of the last item (by date) sent to a user so that next time I can fetch new items from the DB.
Is their any standard way of doing such things?
Just an idea!
I will assume that you make a bean, dao and service layers from your db table that contains the feeds.
At first moment when the page that will retrieve the feeds loads, get all your feeds from a java function and then fill your div with your feeds.
Get the feeds count from your feed container. Now pass the count through jQuery $.post and then to your servlet. To achive this, do the following:
e.g:
//Find divs inside the parent div that will contain your feeds
function getCount(){
return $('#feedContainer').children().find('div').size().toString();
}
//Don't forget to pass it to your jQuery post like this
//(Please, continue reading to understand where to put this)
$.post('/servlet', count:getCount(), function(data){ //manage your new feeds });
Your servlet will receive something like this:
e.g:
String count = request.getParameter("count");
Now that you have the count, verify or just parse as an Integer and then do a list in java. I suppose you have a function to get all your feeds from DB.
e.g:
//Parse it as integer
int feedCountFromUI = Integer.valueOf(count);
//Do a list and call your function to get all feeds from DB.
MyService myService = new MyService();
List<MyBean> feeds = myService.getAll();
//JSON variable
JSONObject result = new JSONObject();
//Fill your JSON variable
for(MyBean mb : feeds) {
//Build a json with your feeds and fill result
}
Suppose that now you have a JSON Object variable called result in your servlet with your feed values filled in the for done above. Now get the count from your list declared as feeds (from above too).
int feedCountFromDB = feeds.size();
You are now close to finish, compare the 2 counts. If the feedCountFromDB it's more than the feedCountFromUI, means that there are new feeds to load.
if(feedCountFromDB > feedCountFromUI){
//Send your json variable (result) to your jquery post callback
out.println(result);
} else {
//Means there is nothing new, print 0
out.println(0);
}
At this point you just need to fill your feed container with the last feed every 5 seconds like this:
(You can add also your jQuery animate function from your jsFiddle at this point)
setInterval(function(){
$.post('/servlet', count:getCount(), function(data){
//If data has feeds (it's not 0)
if(data != 0) {
var lastFeed = data[data.length - 1];
$('#feedContainer').append('<div>' + lastFeed.title + '<br/>' + lastFeed.description + '</div>';
}
});
}, 5000);
This will always check the count from your web interface and then compare it with the count from DB each 5 seconds to get your new feed.
Hope this helps :-)

Java JSONArray from Javascript JSONArray

I am passing a json object from javascript to a java servlet using ajax.
var jsonObj = JSON.stringify(objArray); //Then I pass it to Java using ajax.
In my Java I am getting the json string from the request, then creating a jsonarray, then looping through that array and i'm getting errors when trying to pull one of the json objects from the array.
String dataObj = request.getParameter("obj");
String sql = request.getParameter("sql");
ArrayList<Object> returnArray = new ArrayList<Object>();
int key;
//Get type of object being passed.
JSONArray jsonArray = JSONArray.fromObject(dataObj);
for(int i=0; i<jsonArray.size(); i++) {
String obj = new Gson().toJson(jsonArray.getJSONObject(i)); //This is where i'm getting an error
String className = getClassName(jsonArray.getJSONObject(i));
Class targetClass = null;
try {
targetClass = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//Create Object
Object data = new Gson().fromJson(obj, targetClass);
I'm posting the relevant code, the for loop isn't closed because the rest of the code is quite long, and this is the part where i'm getting the error.
net.sf.json.JSONException: JSONArray[0] is not a JSONObject.
Here is what the json array looks like when its passed in from javascript. This is a println of the jsonArray object.
[{"number":"(123) 456-7050","type":"Home","contactId":1,"id":16662,"className":"beans.PhoneNumber","position":0}]
With one object in it, this code works. But as soon as I get 2 or more, my error comes up.
[[{"number":"(123) 456-7050","type":"Home","contactId":1,"id":16662,"className":"beans.PhoneNumber","position":1},{"number":"(555) 555-1233","type":"Mobile","contactId":1,"id":16656,"className":"beans.PhoneNumber","position":0},{"number":"(999) 999-9999","type":"Home","contactId":1,"id":16664,"className":"beans.PhoneNumber","position":3},{"number":"(222) 222-2222","type":"Home","contactId":1,"id":16666,"className":"beans.PhoneNumber","position":4}]]
It almost looks like when i'm passing more than one object, it create an array of an array, which could be why its not working. But how do I avoid doing that when i'm passing a jsonarray from javascript? Using just the dataObj I have no access to size or get to loop through it.
[
[
{
"number":"(123) 456-7050","type":"Home",
"contactId":1,
"id":16662,
"className":"beans.PhoneNumber",
"position":1
},
{
"number":"(555) 555-1233",
"type":"Mobile",
"contactId":1,
"id":16656,
"className":"beans.PhoneNumber",
"position":0
},
{
"number":"(999) 999-9999",
"type":"Home",
"contactId":1,
"id":16664,
"className":"beans.PhoneNumber",
"position":3
},
{
"number":"(222) 222-2222",
"type":"Home",
"contactId":1,
"id":16666,
"className":"beans.PhoneNumber",
"position":4
}
]
]
This is not an array of objects. This is an array of arrays of objects. According to your description, you are expecting something like the following to be fed to your Java:
[{"foo":"bar"}, {"bar":"baz"}]
But you are really trying to parse:
[[{"foo":"bar"}, {"bar":"baz"}]]
I am not completely sure, because you have not shared the json that you are trying to parse, but the most probable error you have is just what it says: the first element of the array is not JSONObject. Note that string values, lons and booleans are not JSONObjects. I would suggest you to use the more genereal JSONArray.get and check instance of what class it is. Maybe this can head you to the problem with the json you have. If I got it completely wrong - write back and I will try to help. In such a case it will be still useful to share the results of the proposed experiment.
EDIT:
This is double array -> maybe you using getJSONArray(int index) will help you. as the other answer mentioned - this is array of arrays. Also consider changing the javascript to reduce the level of arrays included.

Loading a Dynamic Javascript Tree Structure into a JSP

So I am wanting to read a database, and then form a tree structure and put it in my webpage. I am using the destroydrop tree at the moment, and I can get it to work on its own, but if I want to build the tree and then put it in my webpage, then my page gets overwritten because it uses document.write(tree) to create the tree. I've also tried some other trees which all have the same issue. Anyone know of a tree structure that I can dynamically add to my page without overwriting what is on there? Thanks!
You can try nitobi tree. Nitobi Completeui framework has both client and server sides.
You can find samples in code repository.
Thanks much for the help. I ended up just overriding document.write as such
document.write = function(){
document.getElementById("MyDiv").innerHTML = arguments[0];
}
function getTreeStruct() {
new Ajax.Request('MainServlet', {
method: 'POST',
parameters: "action=getTreeStruct",
onSuccess: function(transport) {
d = new dTree('d');
d.add(0, -1, 'Root Element');
//contains data queried from database to be inserted into the tree.
var responseArray = transport.responseText.split("|");
//Add each element to the tree object
iterate1DArray(function(x) {
var tempArray = x.split(",");
if(tempArray[1] != undefined
&& !(tempArray[0] == 0 && tempArray[1] ==0)){
d.add(tempArray[0], tempArray[1], tempArray[2]);
}
}, responseArray);
document.write(d);
}
});
}
function iterate1DArray(func, array) {
for( var i = 0; i < array.length; i++){
array[i] = func(array[i]);
}
}
I did not include the code for the tree, but it can be found here. Just thought I would put this on here in case anyone else has this type of issue. Thanks again for all your help!

Categories