Json array don't print value in jsp - java

I'm making a dynamic search in jsp.
It begins with Filter.java mapped as filter.json . Using two different methods I correctly save on 2 ArrayList the result of the search on SQL.
This is Filter.java
class Filter() {
...
ArrayList<News> newsListCat = new ArrayList<>();
ArrayList<News> newsListAut = new ArrayList<>();
NewsFactory newsFactory = NewsFactory.getInstance();
String str = request.getParameter("q");
if (str.equals("search")) {
String toSearch = request.getParameter("toSearch");
if (toSearch == null) {
newsListCat = newsFactory.getNews();
} else {
newsListCat = newsFactory.searchNewsbyCat(toSearch);
newsListAut = newsFactory.searchNewsbyAut(toSearch);
//System.out.println(newsListAut);
}
}
request.setAttribute("newsListCat", newsListCat);
request.setAttribute("newsListAut", newsListAut);
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
request.getRequestDispatcher("data.jsp").forward(request, response);
...
}
It send the request in data.jsp that manage json array
<json:array>
<c:forEach var="news" items="${newsListAut}">
<json:object>
<json:property name="type" value="author"/>
<json:property name="newsID" value="${news.getID()}"/>
<json:property name="authorID" value="${news.getAuthor().getID()}"/>
<json:property name="name" value="${news.getAuthor().getName()}"/>
<json:property name="surname" value="${news.getAuthor().getSurname()}"/>
</json:object>
</c:forEach>
<c:forEach var="news" items="${newsListCat}">
<json:object>
<json:property name="type" value="category"/>
<json:property name="authorID" value="${news.getAuthor().getID()}"/>
<json:property name="name" value="${news.getAuthor().getName()}"/>
<json:property name="surname" value="${news.getAuthor().getSurname()}"/>
</json:object>
</c:forEach>
In the end search.js should run the request creating dynamically an unordered list with the result of the query.
The response of request is right, but the jsp page doesn't do anything.
search.js
function stateSuccess(data) {
var ResultCat = $("newsListCat");
$(ResultCat).empty();
var ResultAut = $("newsListAut");
$(ResultAut).empty();
for (var instance in data) {
if (data[instance].type === "category") {
$(ResultCat).append("<li><a href='notizie.html?cat=" + data[instance].category + "'>" + data[instance].category + "</a></li>");
} else if (data[instance].type === "author")
$(ResultAut).append("<a href='profilo.html?id=" + data[instance].authorID + "}'><li>" + data[instance].name + " " + data[instance].surname + "</li></a>");
}
}
function stateFailure(data, state) {
console.log(state);
}
$(document).ready(function () {
$("#search").keyup(function (event) {
//$("input").css("background-color", "rgba(255, 0, 0, 0.8)");
$.ajax({
url: "filter.json",
data: {
q: "search",
toSearch: event.target.value
},
dataType: 'json',
success: function (data, state) {
stateSuccess(data);
},
error: function (data, state) {
stateFailure(data, state);
}
});
});
});
Am I doing anything wrong? I think so but don't know what.
This is how the search request result

By the time you click "search" the jsp page is loaded and is empty.
When you click search, ajax call gets data for you, but the jsp page is not loaded and is still empty.
Use your stateSuccess function to put data in jsp page.

Related

Flow.js and Java Servlet upload file 0 bytes

I added flow.js in my proyect following the instructions and the call to my java servlet:
localhost:8080/WebExample/UploadImgServlet?flowChunkNumber=1&flowChunkSize=1048576&flowCurrentChunkSize=693916&flowTotalSize=693916&flowIdentifier=693916-image2png&flowFilename=image2.png&flowRelativePath=image2.png&flowTotalChunks=1`
In my servlet I get all parameters of the url (flowChuckNumber, flowChuckSize, etc) but when I try to get the file (request.getInputStream()), it's empty and upload 0 bytes.
Where is the problem? Any Idea?
I found a similar question but it was with PHP...
My code:
HTML(the image is displayed):
...
...
<div flow-init="{singleFile:true}"
flow-file-added="!!{png:1,gif:1,jpg:1,jpeg:1}[$file.getExtension()]"
flow-files-submitted="$flow.upload()"
flow-file-success="$file.msg = $message">
<div class="drop" flow-drop ng-class="dropClass">
<md-button class="md-raised md-primary" type="file" flow-btn>Upload Image</md-button>
<b>OR</b>
Drag And Drop your image here
</div>
<div class="thumbnail" ng-show="!$flow.files.length">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="Image"/>
</div>
<div class="thumbnail" ng-show="$flow.files.length">
<img flow-img="$flow.files[0]" />
</div>
<table>
<tr ng-repeat="file in $flow.files">
<td>{{$index+1}}</td>
<td>{{file.name}}</td>
<td>{{file.msg}}</td>
</tr>
</table>
</div>
...
...
App AngularJs:
var app = angular.module("webexample", ['ngMaterial', 'ngNotify','uiGmapgoogle-maps','flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: '/WebExample/UploadImgServlet',
permanentErrors: [404, 500, 501],
maxChunkRetries: 1,
chunkRetryInterval: 5000,
simultaneousUploads: 1
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}])
.directive('appDownloadUrl', [function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('dragstart', function (event) {
var config = scope.$eval(attrs.appDownloadUrl);
if (!config.disabled) {
var data = config.mime + ':' + config.name + ':' + window.location.href + config.url;
console.log("data: "+data);
event.dataTransfer.setData('DownloadURL', data);
}
});
}
};
}])
.directive("appDragstart", [function () {
return function(scope, element, attrs) {
element.bind('dragstart', function (event) {
scope.$eval(attrs.appDragstart);
});
}
}]).directive("appDragend", [function () {
return function(scope, element, attrs) {
element.bind('dragend', function (event) {
scope.$eval(attrs.appDragend);
});
}
}]).run(function ($rootScope) {
$rootScope.dropEnabled = true;
});
My Servlet (I followed this example):
protected void doService(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
LOGGER.debug("[UploadImgServlet - doService] - init");
int resumableChunkNumber = getResumableChunkNumber(request);
ResumableInfo info = getResumableInfo(request);
//info contains all flow parameters of the url.
RandomAccessFile raf = new RandomAccessFile(info.resumableFilePath, "rw");
//Seek to position
raf.seek((resumableChunkNumber - 1) * info.resumableChunkSize);
//Save to file
InputStream is = request.getInputStream();
long readed = 0;
long content_length = request.getContentLength();
//**PROBLEM: request.getContentLength return -1 so read 0 bytes**
byte[] bytes = new byte[1024 * 100];
while(readed < content_length) {
int r = is.read(bytes);
if (r < 0) {
break;
}
raf.write(bytes, 0, r);
readed += r;
}
raf.close();
...
...
The input stream will be empty because flowjs posts the content using MultiPart by default.
The author of the Java code specified that "Octet" should be used for uploads, not multi-part.
UploadServlet accepts Resumable.js Upload with 'octet'
You need to add "method:octet" to your init,
<div flow-init="{singleFile:true, method:octet}"
I am using Spring, so I just used MultipartHttpServletRequest to get the posted data with MultiPart instead because MultiPart is more common.
This is how I received the contents of the file:
Iterator<String> itr = request.getFileNames();
/* Iterate each file, there should only be one/one chunk */
while (itr.hasNext()) {
fileUploaded = request.getFile(itr.next());
raf.write(fileUploaded.getBytes());
}
raf.close();
I had to do more fixes to the java code provided because it was estimating the number of chunks to receive wrong, so I just used the "flowTotalChunks" parameter.
You don't need to worry about content length. The HttpServletRequest will terminate the input stream at the correct point. Just read until end of stream.
I wanted a lib to upload images with more options and visually appealing (drop file from a folder, thumbnail, etc) than the default html input and I have not been able to do with Flowjs and Java Servlet, so I looked for another lib:
https://github.com/danialfarid/ng-file-upload
https://angular-file-upload.appspot.com/
With this lib, I found it easy to use with Java Servlet.
I don't mark this post as solved for if someone finds a way to do it with Flowjs.

Detect java version using deployJava.js ,pops up java upgrade menu

I have a need to know the java version installed on client machine, have come up with the solution here
How to write JavaScript function to check JRE version
When I tried, got with the answer:
console.log(deployJava.getJREs());
But at the address bar, pop up menu is displayed like this
How to hide this?.
If this can not be achieved, please suggest any other idea to implement, as this can not be used,if this popup is not suppressed
I am pretty sure from recent experiments that there is no way to suppress it. For the script to detect the plug-in versions, it must invoke the plug-in itself.
After those experiments I worked to create a script that could detect a variety of things out about the Java plug-in without invoking the plug-in itself. They relied on examining the mime-types info.
This still shows a warning in IE if opened from the local file-system. But I hope it will be more forgiving if loaded from the internet. Please report back.
But note this is what it reports for IE when the 'allow scripts' check is OK'd.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Java Information - Non Deployment Toolkit Script</title>
<meta name='author' content='Andrew Thompson'>
<meta name='description' content='Non Deployment Toolkit Script'>
<script src='mimetypes.js'></script>
<style type='text/css'>
.true {
background-color: #6F6;
}
.false {
background-color: #FB0;
}
.undefined {
background-color: #FF0;
}
.datum {
font-family: monospace;
}
td {
padding: 4px;
}
</style>
</head>
<body>
<h1>Java on this PC</h1>
<h2>Overview</h2>
<p>This page endeavors to ascertain the installation, availability
& version of the Java installed on the client PC.
More importantly, it attempts to discover the information <b>without
invoking the Java Plug-In</b> itself.
The last part is what makes it different
to the Deployment Toolkit Script supplied by Oracle.
</p>
<script type='text/javascript'>
document.write("<h2>Browser Info.</h2>");
document.write(getBrowserInfo());
document.write("<h2>Basic Info.</h2>");
document.write("<table border='1'>");
document.write(get3CellRow('<b>Enabled</b>', isJava(), 'Java is enabled (1.1+) - IE info. (short of ActiveX) stops here'));
document.write(get3CellRow('<b>Version</b>', getVersion(), 'Maximum version reliably <em>known</em> to be available'));
if (isIE()) {
document.write(get3CellRow('<b>MSIE</b>', getIEVersion(), 'Maximum version reliably known to be available in IE, tested using ActiveX'));
}
document.write(get3CellRow('<b>JWS</b>', isJWS(), 'Java Web Start available (1.4.2+)'));
document.write(get3CellRow('<b>Plug-In 2</b>', isPlugin2(), 'Plug-In 2 available (1.6.0_10+)'));
document.write("</table>");
if (plugins.length>0) {
document.write("<h2>Navigator Plug-Ins</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Name</th><th>Version</th><th>File Name</th><th>Description</th></tr>");
for (var ii=0; ii<plugins.length; ii++) {
var t = plugins[ii].name;
if (t.indexOf("Java")>-1) {
document.write("<tr>");
document.write("<td>" + plugins[ii].name + "</td>");
document.write(getDataStyledCell(plugins[ii].version));
document.write("<td>" + plugins[ii].filename + "</td>");
document.write("<td>" + plugins[ii].description + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
if (mimes.length>0) {
document.write("<h2>Navigator Mime-Types</h2>");
document.write("<table border='1'>");
document.write("<tr><th>Mime</th><th>Description</th><th>Types</th></tr>");
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
((t.indexOf("jpi")>0 || t.indexOf("deploy")>0 || t.indexOf("jnlp")>0 || t.indexOf("vm")>0) ||
mimes[ii].description.length>0)
) {
document.write("<tr>");
document.write("<td>" + mimes[ii].type + "</td>");
document.write("<td>" + mimes[ii].description + "</td>");
document.write("<td>" + mimes[ii].suffixes + "</td>");
document.write("</tr>");
}
}
document.write("</table>");
}
</script>
<hr>
<h2>Description</h2>
<p>In order (if available) the information is:
<ul>
<li><b>Browser info. Table:</b> Not strictly related to Java - the
information in the other tables is determined without
further reference to any information shown in this table (except for the <code>appName</code> used for
identifying IE).
OTOH it is an helpful guide
as to what we should be <em>expecting</em>
from the other information. E.G. IE
will not show the Plug-In or Mime Type tables. <em>Only</em>
FF displays the plug-in version numbers.
</li>
<li><b>Basic info. Table</b>
<ul>
<li><b>Enabled</b>: Java is known to this browser and enabled, according to JavaScript <code>navigator.javaEnabled()</code>.</li>
<li><b>Version</b>: The maximum Java version known to be supported in this browser/PC.
It is set to <code>1.1</code> if the previous check is <code>true</code>, since the MSVM
was the first Java version the public could get in a browser, and the MSVM
implemented Java 1.1. Goes on to check
<code>application/x-java-applet;jpi-version</code>
in the mime types if available
(i.e. typically browsers that are <em>not</em> IE).
</li>
<li><b>MSIE</b> (IE Only): The maximum Java version known to be supported by this instance of Internet Explorer
as determined using ActiveX. It runs from 1.4.2, 1.5.0.. through 1.9.0.
</li>
<li><b>JWS</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was co-bundled.</li>
<li><b>Plug-In 2</b>:
Inferred from a comparison of the version to the Sun JRE in which
it was introduced.</li>
</ul>
</li>
<li><b>Navigator Object Tables:</b>
<em>The rest of the info. is gleaned from the <code>navigator</code> object.
IE does not include this information.</em>
<ul>
<li><b>Plug-Ins</b>: More details of the Java related plugins.
Filtered for <code>Java</code> in the <code>name</code>.
A <code>description</code> showing "Next Generation Java Plug-in" or <code>name</code>
"Java Deployment Toolkit" should be 1.6.0_10+.</li>
<li><b>Mime-Types</b>: More information on the Java related Mime-Types.
Filtered in <code>mime</code> field for <code>'java'</code> + <code>('jpi'||'vm'||'deploy')</code>
or a non-empty <code>description</code>.
The value <code>java-deployment-toolkit</code> in the <code>mime</code>
is a good indicator of 1.6.0_10+.
</li>
</ul>
</li>
</ul>
</body>
</html>
mimetypes.js
// As a version string, this might be '1.4.2_31'.
// I.E. it is not a 'number' but a 'string' and therefore must be treated as a string.
var highestVersion = 'undefined';
var mimes = window.navigator.mimeTypes;
var plugins = window.navigator.plugins;
function isJava() {
return (
typeof(navigator.javaEnabled) !== 'undefined' &&
navigator.javaEnabled());
}
function getVersion() {
var version = 0;
if (isJava()) {
version = 1.1;
}
for (var ii=0; ii<mimes.length; ii++) {
var t = mimes[ii].type;
if (t.indexOf("java")>0 &&
t.indexOf("jpi")>0 &&
t.indexOf("applet")>0
) {
var parts = t.split("=");
version = parts[parts.length-1];
}
}
if (highestVersion=='undefined') highestVersion = version;
return version;
}
function isJWS() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.4.2') {
className = true;
}
return className;
}
function isPlugin2() {
var ver = highestVersion;
var className = false;
if (ver>'1.0') {
className = undefined;
}
if (ver>'1.6.0_10') {
className = true;
}
return className;
}
var versionFamily = [
'1.9.0', '1.8.0', '1.7.0',
'1.6.0', '1.5.0', '1.4.2'
];
function getIEVersion() {
for (var i=0; i<versionFamily.length; i++) {
if (testUsingActiveX(versionFamily[i])) {
return versionFamily[i];
}
}
return false;
}
if (isIE() && getVersion()=='1.1') {
highestVersion = getIEVersion();
}
function isIE() {
return navigator.appName=='Microsoft Internet Explorer';
}
function testUsingActiveX(version) {
var objectName = 'JavaWebStart.isInstalled.' + version + '.0';
// we need the typeof check here for this to run on FF/Chrome
// the check needs to be in place here - cannot even pass ActiveXObject
// as arg to another function
if (typeof ActiveXObject == 'undefined' || !ActiveXObject) {
alert('[testUsingActiveX()] Browser claims to be IE, but no ActiveXObject object?');
return false;
}
try {
return (new ActiveXObject(objectName) != null);
} catch (exception) {
return false;
}
}
function get3CellRow(cell1, cell2, cell3) {
var s = "" +
"<tr>" +
"<td class='" +
getClassName(cell1) +
"'>" +
cell1 +
"</td>" +
getDataStyledCell(cell2) +
"<td class='" +
getClassName(cell3) +
"'>" +
cell3 +
"</td>" +
"</tr>" +
"";
return s;
}
function getDataStyledCell(value) {
var s = "<td class='datum " +
getClassName(value) +
"'>" +
value +
"</td>";
return s;
}
function getClassName(val) {
var className = undefined;
if (
(val) ||
(!val) ||
(val!=="undefined")
) {
className = val;
}
return className;
}
function getBrowserInfo() {
var s = "";
var props = [
'appCodeName','appName','appVersion',
'userAgent',
'platform','cookieEnabled'
];
s += "<table border='1'>";
for (var i=0; i<props.length; i++) {
s+= "<tr>";
s+= "<td><b>";
s+= props[i];
s+= "</b></td>";
s+= "<td>";
s+= navigator[props[i]];
s+= "</td>";
s+= "</tr>";
}
s += "</table>";
return s;
}
Please note (be warned) this script was written by me, a Java programmer. Java programmers are typically the absolute worst people on the planet for writing JS, since we foolishly tend to presume. "It's JavaScript, how hard can it be?".
To write really good JavaScript is indeed an art.
Even worse, this was experimental code that was 'hacked out' with the intention of improving it later, but the project was abandoned and 'later' never arrived.
Caveat emptor.

Unable to call a function with ENTER key

I need to pass in some values to my function
I want the function to run when I press ENTER KEY in PHP
the function is update()
This is my PHP
echo '<input type="text" size="23" id= n'.$row["ContactID"].'
class = "name" placeholder="Contact Name"
value="'.$row["Name"].'
onkeydown="if (event.keyCode == 13) updatename(this,'.$row["ContactID"].') ">';
my javascript
function updatename(item, cid)
{
var varname = $(item).val();
var originaltext = $(item).val();
$.ajax({
url: 'changeContact.php',
type: 'POST',
data:{
varname: varname
},
success:function (data) {
if (data == '1')
{
$("#status")
.addClass("success")
.html("Data saved successfully")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
else
{
$("#status")
.addClass("error")
.html("An error occured, the data could not be saved")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
}
});
}
Why does it don't seem to be working? Nothing have been send to my database, even I change to a simple alert, nothing appear
How can I improve it?
Probably because your HTML is invalid.
...
value="'.$row["Name"].' <--------- " is missing
onkeydown="if (eve...
<input type="text" id="your id" onkeypress="MAGIC(event);" />
function MAGIC(event){
$("#id").keyup(function(event){
if(event.keyCode == 13){
//your code to be executed
}
}

Issue with jqGrid and jquery next and previous click event

I am trying to click on the next button but it doesn't work, it happens only when i click on the search button and he result appears from the first page, but then wen i click on the next page button it doesn't work can anyone please help: the code is below:
<script type="text/javascript">
var initGridUri = '<%=request.getContextPath()%>/searchNodeAlerts.action?rand=<%=rand%>';
var qs = window.location.search.substring(1);
var qsArray = qs.split('&');
var qsSearch;
var qsKeyword;
var qsSource;
var s;
for (i=0;i<qsArray.length;i++) {
var cs = qsArray[i].split('=');
if (cs[0] == 'as'){
qsSearch = cs[1];
} else if (cs[0] == 'k'){
qsKeyword = cs[1];
} else if (cs[0] == 'sn'){
qsSource = cs[1];
}
}
myStack = new Array();
$(document).ready(function(){
if (qsSearch == 'true'){
initGridUri = '<%=request.getContextPath()%>/searchNodeAlerts.action?rand=<%=rand%>&keyword='+ qsKeyword +'&sourceNumber='+ qsSource;
}
$("#workspace").tabs();
$("#bin-search-submit").live('click',function(){nodeSearchSubmit()})
$("#bin-search-reset").click(function(){binSearchReset()});
$("#bin-search-publish-start, #bin-search-publish-end").datepicker();
$("#bin-advanced-search").toggle(
function(){
$("#bin-search").animate({height:435}, 500);
$(this).removeClass('ui-icon ui-icon-arrowstop-1-s');
$(this).addClass('ui-icon ui-icon-arrowstop-1-n');
},
function(){
$("#bin-search").animate({height:110}, 500);
$(this).removeClass('ui-icon ui-icon-arrowstop-1-n');
$(this).addClass('ui-icon ui-icon-arrowstop-1-s');
}
)
$("#bin-search-source").change(function(){binSearchSource(this)})
$("#refGrid").jqGrid({
jsonReader : {
root: "serachResultList",
page: "page",
total: "total",
records: "records",
repeatitems: false
},
datatype: function(postdata) {
jqGridDataRequest(initGridUri, postdata, "refGrid",'onGridLoadComplete()')
},
<sh:hztClientPref reverse="false" prefname="RELATED_ALERTS" value="Enabled">
colNames:['Actions','Recall #','Title', 'Source', 'Source No','Date','Status','RefID', 'Related'],
</sh:hztClientPref>
<sh:hztClientPref reverse="false" prefname="RELATED_ALERTS" value="Disabled">
colNames:['Actions','Recall #','Title', 'Source', 'Source No','Date','Status','RefID'],
</sh:hztClientPref>
colModel:[
{name:'act',index:'act', width:85, sortable:false},
{name:'hztNumber',index:'hztNumber', width:80, sortable:true},
{name:'title',index:'title', width:205, formatter:newLine},
{name:'source',index:'source', width:50, sortable:true},
{name:'sourceAlertNumber',index:'sourceAlertNumber', width:55, sortable:false},
{name:'receivedDate', index:'receivedDate', width:70, formatter:newDate, sortable:true},
{name:'status',index:'status', width:50, sortable:false},
{name:'refId',index:'refId', hidden:true},
<sh:hztClientPref reverse="false" prefname="RELATED_ALERTS" value="Enabled">
{name:'relatedAlertPresent',index:'relatedAlertPresent', hidden:true}
</sh:hztClientPref>
],
rowNum:20,
height:'auto',
viewrecords: true,
pgbuttons: true,
sortname: 'receivedDate',
sortorder: 'desc',
pager: '#refPager',
multiselect: true
})
});
function nodeSearchSubmit(){
var keyword = $('input[name=keyword]');
var title = $('input[name=title]');
var sourceNumber = $('input[name=sourceNumber]');
var startReceiveDate = $('input[name=startReceiveDate]');
var endReceivedate = $('input[name=endReceiveDate]');
var source = $('select[name=source]');
var status = $('select[name=status]');
var recallNo = $('input[name=recallNo]');
var page = $('page');
var data = 'keyword='+ keyword.val() +'&title='+ title.val() +'&sourceAlertNumber='+ sourceNumber.val() +'&startReceiveDate='+ startReceiveDate.val()
+'&endReceiveDate='+ endReceivedate.val() +'&source='+ source.val() + '&status='+status.val() + '&hztNumber='+recallNo.val();
var request = '<%=request.getContextPath()%>/searchNodeAlerts.action?rand=<%=rand%>&page=1&'+ data;
<%=rand%>' + data;
initGridUri = request;
jQuery("#refGrid").trigger("reloadGrid")
}
There isnt enough information here to answer this question with any certainty. You should include the response from the server after clicking the next button.
If i had to guess i would say that the response contains javascript that either causes a js error on page, or overwrites some variable causing the next button to break.
does the response contain javascript?

Flex/Flash 4 datagrid displays raw xml

Problem: Flex/Flash4 client (built with FlashBuilder4) displays the xml sent from the server exactly as is - the datagrid keeps the format of the xml. I need the datagrid to parse the input and place the data in the correct rows and columns of the datagrid.
flow: click on a date in the tree and it makes a server request for batch information in xml form. Using a CallResponder I then update the datagrid's dataProvider.
[code]
<fx:Script>
<![CDATA[
import mx.controls.Alert;
[Bindable]public var selectedTreeNode:XML;
public function taskTreeChanged(event:Event):void {
selectedTreeNode=Tree(event.target).selectedItem as XML;
var searchHubId:String = selectedTreeNode.#hub;
var searchDate:String = selectedTreeNode.#lbl;
if((searchHubId == "") || (searchDate == "")){
return;
}
findShipmentBatches(searchDate,searchHubId);
}
protected function findShipmentBatches(searchDate:String, searchHubId:String):void{
findShipmentBatchesResult.token = actWs.findShipmentBatches(searchDate, searchHubId);
}
protected function updateBatchDataGridDP():void{
task_list_dg.dataProvider = findShipmentBatchesResult.lastResult;
}
]]>
</fx:Script>
<fx:Declarations>
<actws:ActWs id="actWs" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/>
<s:CallResponder id="findShipmentBatchesResult" result="updateBatchDataGridDP()"/>
</fx:Declarations>
<mx:AdvancedDataGrid id="task_list_dg" width="100%" height="95%" paddingLeft="0" paddingTop="0" paddingBottom="0">
<mx:columns>
<mx:AdvancedDataGridColumn headerText="Receiving date" dataField="rd"/>
<mx:AdvancedDataGridColumn headerText="Msg type" dataField="mt"/>
<mx:AdvancedDataGridColumn headerText="SSD" dataField="ssd"/>
<mx:AdvancedDataGridColumn headerText="Shipping site" dataField="sss"/>
<mx:AdvancedDataGridColumn headerText="File name" dataField="fn"/>
<mx:AdvancedDataGridColumn headerText="Batch number" dataField="bn"/>
</mx:columns>
</mx:AdvancedDataGrid>
//xml example from server
<batches>
<batch>
<rd>2010-04-23 16:31:00.0</rd>
<mt>SC1REVISION01</mt>
<ssd>2010-02-18 00:00:00.0</ssd>
<sss>100000009</sss>
<fn>Revision 1-DF-Ocean-SC1SUM-Quanta-PACT-EMEA-Scheduled Ship Date 20100218.csv</fn>
<bn>10041</bn>
</batch>
<batches>
[/code]
and the xml is pretty much displayed exactly as is shown in the example above in the datagrid columns...
I would appreciate your assistance.
I tried a simplified version of your sample using a simple xml literal, and it works fine for me..
here's what I've got
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function onCreationCompleteHandler(event:FlexEvent):void
{
task_list_dg.dataProvider = data..batch;
}
private var data:XML = //xml example from server
<batches>
<batch>
<rd>2010-04-23 16:31:00.0</rd>
<mt>SC1REVISION01</mt>
<ssd>2010-02-18 00:00:00.0</ssd>
<sss>100000009</sss>
<fn>Revision 1-DF-Ocean-SC1SUM-Quanta-PACT-EMEA-Scheduled Ship Date 20100218.csv</fn>
<bn>10041</bn>
</batch>
</batches>;
]]>
</fx:Script>
<mx:AdvancedDataGrid id="task_list_dg" width="100%" height="95%" paddingLeft="0" paddingTop="0" paddingBottom="0">
<mx:columns>
<mx:AdvancedDataGridColumn headerText="Receiving date" dataField="rd"/>
<mx:AdvancedDataGridColumn headerText="Msg type" dataField="mt"/>
<mx:AdvancedDataGridColumn headerText="SSD" dataField="ssd"/>
<mx:AdvancedDataGridColumn headerText="Shipping site" dataField="sss"/>
<mx:AdvancedDataGridColumn headerText="File name" dataField="fn"/>
<mx:AdvancedDataGridColumn headerText="Batch number" dataField="bn"/>
</mx:columns>
</mx:AdvancedDataGrid>
Are you sure your data is arriving in the format you're suggesting?
(check the Data/Services tab in FB)
What do you mean by "displays the xml sent from the server exactly as is - the datagrid keeps the format of the xml" ? does it dump xml content in the grid cells?
Edit: Have you tried doing this?
protected function updateBatchDataGridDP():void{
task_list_dg.dataProvider = findShipmentBatchesResult.lastResult..batch;
}
had to resort to this monstrosity ----> is there a better way???
protected function updateBatchDataGridDP():void{
var batches:XML = new XML(findShipmentBatchesResult.lastResult);
task_list_dg.dataProvider = batches.batch;
var task_list_col1:AdvancedDataGridColumn = new AdvancedDataGridColumn();
task_list_col1.dataField = "#rd";
task_list_col1.headerText = "Receiving date";
var task_list_col2:AdvancedDataGridColumn = new AdvancedDataGridColumn();
task_list_col2.dataField = "#mt";
task_list_col2.headerText = "Msg type";
var task_list_col3:AdvancedDataGridColumn = new AdvancedDataGridColumn();
task_list_col3.dataField = "#ssd";
task_list_col3.headerText = "SSD";
var task_list_col4:AdvancedDataGridColumn = new AdvancedDataGridColumn();
task_list_col4.dataField = "#sss";
task_list_col4.headerText = "Shipping site";
task_list_status.text = batches.batch.#sss;
var task_list_col5:AdvancedDataGridColumn = new AdvancedDataGridColumn();
task_list_col5.dataField = "#fn";
task_list_col5.headerText = "File name";
var task_list_col6:AdvancedDataGridColumn = new AdvancedDataGridColumn();
task_list_col6.dataField = "#bn";
task_list_col6.headerText = "Batch number";
var myColumns:Array = new Array();
myColumns.push(task_list_col1);
myColumns.push(task_list_col2);
myColumns.push(task_list_col3);
myColumns.push(task_list_col4);
myColumns.push(task_list_col5);
myColumns.push(task_list_col6);
task_list_dg.columns = myColumns;
}
with this xml structure:
<batches>
<batch rd="2010-04-23 16:31:00.0" mt="SC1REVISION01" ssd="2010-02-18 00:00:00.0" sss="Quanta" fn="Revision 1-DF-Ocean-SC1SUM-Quanta-PACT-EMEA-Scheduled Ship Date 20100218.csv" bn="SHA201004230033" />
<batch rd="2010-04-23 16:32:14.0" mt="SC1" ssd="2010-02-11 00:00:00.0" sss="Quanta" fn="DF-Ocean-SC1SUM-Quanta-PACT-EMEA-Scheduled Ship Date 20100211.csv" bn="SHA201004230043" />
<batch rd="2010-04-23 16:35:51.0" mt="PRESHIP" ssd="2010-02-15 00:00:00.0" sss="Quanta" fn="DF-Ocean-PRESHIPSUM-Quanta-PACT-EMEA-Scheduled Ship Date 20100215.csv" bn="SHA201004230045" />
</batches>

Categories