I am attempting to send over an XML string to Flex via javascript. This is the XML I am creating with javascript.
var xml = "<template>";
xml += "<folder>";
xml += "<lab>";
xml += "Are You working?";
xml += "</lab>";
xml += "</folder>";
xml += "</template>";
return xml;
I have confirmed that "<template><folder><lab>Are you working</lab></folder></template>" is getting sent via an Alert box.
In the Flex application here is where thing are going wrong. I am calling this function on creationComplete and attempting to populate a comboBox:
/ variable declarations---------------------------------------
[Bindable]
private var templateFolder:ArrayCollection = new ArrayCollection();
// event handlers-----------------------------------------------
private function init(event:FlexEvent):void {
var labList:SyncRequestResult=CSXSInterface.instance.evalScript("templateHub");
templateFolder = labList.data.template.folder;
}
/ variable declarations---------------------------------------
[Bindable]
private var templateFolder:ArrayCollection = new ArrayCollection();
// event handlers-----------------------------------------------
private function init(event:FlexEvent):void {
var labList:SyncRequestResult=CSXSInterface.instance.evalScript("templateHub");
templateFolder = labList.data.template.folder;
}
And then finally to my component:
<mx:ComboBox id="labFolderList"
x="53" y="11"
width="212"
dataProvider="{templateFolder}"
labelField="lab"></mx:ComboBox>
I'm a newbie at Flex and not sure that I am treating the data correctly in Flex. Any ideas where I am screwing this up?
Thanks for your help
Related
I need to draw a table dynamically depending on the data store in a database. When the first web page (validator.jsp) is loaded it goes to a dataBase and returns an ArrayList called cert. (cert hast Description, value, etc).
<% java.util.ArrayList<Certificate> cert = OperacionesVidaDollars.getCertificates();%>
After that when the page finishes loading, a javascript function is called (function drawCertificates). This function will draw as many tables as certificates the ArrayList has.
<script type="text/javascript">
window.onload = drawCertificates;
function drawCertificates(){
alert("page finish loading, staring to draw certificates");
var i;
for(i=0;i<<%=cert.size()%>;i++){
createTable(i);
}
}
</script>
As you can see in the function create table, the variable text is suppost to change depending on i
text = document.createTextNode("<%=cert.get(i).getDescription()%>");
In order to update that variable i, I first call the JSP setVariable, to update the counter and then I try to use it in getDescription like:
text = document.createTextNode("<%=cert.get(request.getAttribute("count")).getDescription()%>");
I have this setVariable.jsp
<%
int num = Integer.valueOf(request.getParameter("number"));
request.setAttribute("count", num);
request.getRequestDispatcher("VidaDollarsCC.jsp").forward(request, response);
Cookie cookie = new Cookie("countCookie",String.valueOf(num));
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
%>
In other JSP (validator.jsp)I have this javascript function who it supposed to change the variable value.
function setVariable(number){
alert("setting the number " + number);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
}
xmlhttp.open("POST", "setVariable.jsp", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("number="+number);
}
In the same jsp (validator.jsp) I have this function to createTable(uniqID) where I need that the number is updated depending on the uniqID because I have an ArrayList which has some information that I want to be shown.
function createTable(uniqID){
setVariable(uniqID);
text = document.createTextNode("<%=cert.get(request.getAttribute("count")).getDescription()%>");
}
But is not working. Does someone knows why? How can I solve it? if you have other ideas that I can implement, that also would be great.
I am assuming that your AJAX call is successfully sending number to setVariable.jsp.
1) You have to realize that AJAX call is a different request and is different then the request you have in your validator.jsp page.
2) You cant write JSP expression from Javascript and have it being resolved to HTML since your JSP needs to be reprocessed by server side.
To answer to your question on how to solve this, we need to know what you are trying to do in the first place.
Update:
1) Looks like the uniqID and count are same number. Why not just use uniqID in your javascript.
2) Why not pass certificate description into the createTable too. Like so:
<% java.util.ArrayList<Certificate> cert = OperacionesVidaDollars.getCertificates();
StringBuilder jsCerts = new StringBuilder("[");
boolean first = true;
for (Certificate cr : certs){
if (!first) jsCerts.append(",");
first = false;
jsCerts.append("\"").append( cr.getDescription() ).append("\"");
}
jsCerts.append("]");
%>
<script type="text/javascript">
window.onload = drawCertificates;
function drawCertificates(){
alert("page finish loading, staring to draw certificates");
var certArray = <%=jsCerts.toString()%>;
var i;
for(i=0;i<certArray.length;i++){
createTable(i, certArray[i]);
}
}
</script>
function createTable(uniqID, desc){
setVariable(uniqID);
text = desc;
}
The point here is that you need to write all the necessary data into the HTML to be able to use it in JavaScript, you cant access request attributes from JavaScript.
I am trying to add create an editable table in HTML. So, I need to add rows, when user clicks on a button. Here is the code I am using.
//remove all old rows.
while (summaryTableElement.firstChild) {
summaryTableElement.removeChild(summaryTableElement.firstChild);
}
//add a new text area in the summary field.
summaryTableElement.innerHTML = "<textarea id='summaryTextBox' value='' onblur='saveSummary()'> </textarea> ";
This code works fine on Chrome and Mozilla. But, IE doesn't allow editing innerHTML. This HTML will be displayed inside a VB form, so I have "browser" and "webbrowser" controls available. Both of those controls use IE engine, so this code does not work there.
I have tried using firstchild.innerHTML instead so that I am not editing table row directly, and even that gave me same error.
I tried using WebKitBrowser. But, that causes an exception on load. Apparently that control uses some old method, and the method is changed. So, that control is out of question too.
Now, I am confused as to how to solve this problem?
Edit:
I found the issue with WebKitBrowser. It was specific to x86, while my project was targeting both x64 and x86. Switching it to x86 for both, worked. Although, webkit browser do not take return key values. So, I have a new problem. Pressing enter does not create a new line in table cell, and instead passes the event to vb form.
Edit:
Okay, so I tried working further with WebKitBrowser. But, that control gives me accessviolatedexception. So, I am thinking about going back to using the default browser control, for now.
As for default control, I checked further. Apparently, code works fine in IE9 and above. But, vb.net control uses some weird JS engine. So, I am receiving error only in vb control.
Here is the complete code for reference:
var summaryChanges = "";
var isSummaryClickable = true;
//creates a textbox for editing purpose and include the original summary data.
function modifySummary(id) {
var summaryTableElement; //to get the table cells so that we can access the value
var originalSummary = ""; //to hold the original summary while we create a text box
var loopCounter = 0;
if (isSummaryClickable == true) {
isSummaryClickable = false; //saves event spilling when clicked on the newly created textbox
//get the summary table id saved.
summaryTableElement = document.getElementById (id).childNodes.item(0);
//add existing data to a string to save it for later.
for (loopCounter = 0; loopCounter < summaryTableElement.childNodes.length; loopCounter++) {
originalSummary = originalSummary + summaryTableElement.childNodes.item(loopCounter).childNodes.item(0).innerHTML + "\n";
}
//remove all old rows.
while (summaryTableElement.firstChild) {
summaryTableElement.removeChild(summaryTableElement.firstChild);
}
//add a new text area in the summary field.
summaryTableElement.innerHTML = "<tr><td><textarea id='summaryTextBox' value='' onblur='saveSummary()'> </textarea></td></tr> ";
//set the width of the textbox to allow easy modification
document.getElementById("summaryTextBox").style.width = '600px';
//add original summary text to the text area and set focus
document.getElementById("summaryTextBox").value = originalSummary;
document.getElementById("summaryTextBox").focus();
}
}
// saves the updated summary data back to HTML
function saveSummary()
{
var newHTML = "";
var changesSummary;
var changesSubString = new Array();
var index = 0;
var elementToUpdate;
//get the summary table id saved.
elementToUpdate = document.getElementById("SummaryData"); //.childNodes.item(0);
//get changes from the textbox
changesSummary = document.getElementById("summaryTextBox").value;
//generate string array for separate lines from summaryChanges
changesSubString = changesSummary.split("\n");
//generate new HTML string for the summary fields
//alert(changesSubString.length);
for (index = 0; index < changesSubString.length; index++) {
newHTML = newHTML + "<tr><td class='Text' style='padding-left: 4px;padding-bottom: 4px;' id='SummaryLine" + index + "'</td>" + changesSubString[index] + "</tr>"
}
//update the HTML to the element
elementToUpdate.innerHTML = newHTML;
//allow clicking on summary table
isSummaryClickable = true;
}
function doNothing(id) {
//empty function for future use
return;
}
//this function is called from vb.net script to read the js variable.
//do not change the function definition (name or parameters or return type)
//any change will cause error in vb.net script
function jsInvokedFunction() {
var updatedHTML; // to be used by vb.net invoked function to get updated body
var testVariable = "test";
updatedHTML = document.body.innerHTML.toString();
return updatedHTML.toString();
}
I receive an error at the start of the line summaryTableElement.innerHTML = " ";
It is possible I am missing some other error, but I couldn't find any.
I have a AJAX response something like this.
[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}]<table id="table"></table>
It has both JSON and HTML in the response.
I wanted to separate those two things.
And use the JSON for a chart function I've created.
And then append that table to a div.
Any suggestions will be very much fruitful.
Thanks in advance.
In php
$array = 'Your json array';
$html = 'Your html codes';
Make a single array with two keys
$newArray = array();
$newArray['json'] = $array;
$newArray['html'] = $html;
echo json_encode($newArray);
In Jquery
DataType: 'JSON',
success:function(response){
response.json = 'This is your json';
response.html = 'This is your html';
}
Add the HTML to the JSON response and use it like you would your other values (make sure to escape your html). Also use JSONLint to make sure your JSON is valid.
[
{
"label": "label",
"label1": "67041",
"label2": "745",
"label3": "45191",
"label4": "11464",
"html": "<table id=\"table\"></table>"
}
]
While I recommend you not to do that, because is to geeky and hard to maintain, You can solve id by detecting the JSON object using regex, like this:
var data = '[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}]<table id="table"></table>';
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str.substr(1, json_str.length-2) + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}
//html_data = [text] <table id="table"></table>
The Best Solution would be to use a template engine like jquery templates to define your html, and then get your data via $.json and evaluate it agains your desired template already on the client, no need to be sending it right along with your data and be doing that kind of processing in run time.
JavaScript
// assuming you keep receiving this
var data =
'[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"},'
+'{"label":"label2","label1":"0000","label2":"222","label3":"333","label4":"11333"}]'
+'<table id="table"></table>';
// parse the data with regex
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1": ...
//html_data = [text] <table id="table"></table> ...
// then use jquery templates to render it
var data = json_data;
$('body').append(html_data);
$('#trTemplate').tmpl(data).appendTo('#table');
HTML
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${label}</td>
<td>${label1}</td>
<td>${label2}</td>
<td>${label3}</td>
<td>${label4}</td>
</tr>
</script>
CSS
#table, td{ border:1px solid #000; padding:5px; }
Here is an working JSFiddle example for you to test it.
Note how this works when you have more than one {json object, it's creates more lines in the table :) }
If you use jquery templates only, and now assuming that you can actually modify your output than the best thing to do is:
New JavaScript Version of Code with template only and no HTML on 'data'
$.json('http://server.com/url/service/someservice.something', function(data){
$('body').append(<table id="#table></table>");
$('#trTemplate').tmpl(data).appendTo('#table');
})
Much more simple don't you think?! Hope this helps guiding you on the right path.
Link to jquery tmpl: http://knockoutjs.com/downloads/jquery.tmpl.min.js.
Although after understanding my example, if you are building a system to scale on, and you are not just doing a simple widget app, I would recommend you to check something more robust in terms of functionalities and support like Knockoutjs as jquery tmpl has been deprecated, unfortunately.
I am using the replaceWith() function in jQuery to update my web page. I receive the data from a C# web service program that extracts data from a database to build my HTML code. It works fine except when I replace large amounts of data. In the example that's not working, I replace code in my web page with 39000 bytes of data. After that, none of my links work when clicking on a span to calls a JavaScript function. Is there a limit on the size of data used in the replaceWith() function? The html code I am replacing looks like this:
<td align=left valign=top>
<div id="showitems" class="showitems" style="display:inline; float:left"></div>
</td>
The javascript code looks like this:
function ShowDinerItems() {
var gps = document.getElementById("selectdiner").value;
var pos = gps.indexOf(";");
var len = gps.length;
var latitude = document.getElementById("Hiddenlat").value;
var longitude = document.getElementById("Hiddenlng").value;
var dinerkey = gps.substring(0, pos);
PageMethods.CallShowDinerItems(dinerkey, latitude,longitude, OnShowDinerComplete, OnShowDinerError, dinerkey);
}
function OnShowDinerComplete(result) {
var htmlcode = result[0];
if (result == 'none') {
document.getElementById("Message").value = "Search returned no items";
}
else {
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
var locations = result[1].split(";");
var lat = locations[0];
var lng = locations[1];
markDiner(lat, lng, "", 'map_canvas');
}
}
The reason I am using jquery to build my webpage is to avoid page reloads. I could easily program the webdata content in my C# program which may be more efficient but page reloads are to be avoided as dictated by the people who own the website. I am will try the recommendations given.
Note: I used the following code to make it work.
$('.showitems').html(result[0]);
Using .text will not work as it displays raw data and not html data. Thanks to those who contributed.
To be honest I think you're going about this the wrong way here.
It seems to me that you're using ReplaceWith to completely overwrite the matched tag when you could just as simply change its properties with jQuery.
For example:
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
Could easily be changed to this:
$('.showitems').css('float','none').text(result[0]);
Just how many showItems are there going to be by the way, and how do you know how it compares to how many results you get back from the C# call ?
Edit 2: Sorry, didn't realise that the CSS display attribute wasn't actually changing.
With below code, I am trying to match a text in a web page to get rid of html tags in a page.
var body = $(body);
var str = "Search me in a Web page";
body.find('*').filter(function()
{
$(this).text().indexOf(str) > -1;
}).addClass('FoundIn');
$('.FoundIn').text() = $('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>");
But it does not seems to work.. Please have a look at this and let me know where the problem is...
here is the fiddle
I have tried the below code instead..
function searchText()
{
var rep = body.text();
alert(rep);
var temp = "<font style='color:blue; background-color:yellow;'>";
temp = temp + str;
temp = temp + "</font>";
var rep1 = rep.replace(str,temp);
body.html(rep1);
}
But that is totally removing html tags from body...
change last line of your code to below one...you are using assignment operator which works with variables not with jquery object ..So you need to pass the replaced html to text method.
$('.FoundIn').text($('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>"))
try this.
$('*:contains("Search me in a Web page")').text("<span class='redT'>Search me in a Web page</span>");