How to pass values from HTML page to java applet? - javascript

I have tried passing values using javascript like below
<script language= "javascript" type= "text/javascript">
var num;
function getVal()
{
num=document.getElementById('in').value;
alert(document.getElementById('parm').value);
}
</script>
<body>
<form >
Number : <input type="text" id="in" ><br/>
<button id="myBtn" onclick="getVal()">Try it</button><br/>
</form>
<APPLET code="Calc.class" width="100" height="100">
<PARAM name="number" id="parm">
</APPLET>
</body>
</html>
The alert box displays the entered value on screen but the applet code is not displaying the same. My applet code is
public class Calc extends Applet
{
private String strDefault = "Hello! Java Applet.";
public void paint(Graphics g) {
String strParameter = this.getParameter("number");
if (strParameter == null)
strParameter = strDefault;
g.drawString(strParameter, 10, 10);
}
}
Can anyone tell me the code to pass and retrieve values to and from param tag to html?

I think you can specify your parameters from javascript objects like so:
<applet code="Calc.class" width="100" height="100">
<param name="number" id="parm" value="&{num};">
</applet>
However, I'm not sure of the compatibility with IE so you may have to document.write out your applet code injecting the respective parameter values like so:
<head>
<script type="text/javascript">
var num;
function getVal() {
num = document.getElementById('in').value;
writeAppletTags();
}
function writeAppletTags() {
var container = document.getElementById("applet-container");
container.innerHTML = "<applet code=\"Calc.class\" width=\"100\" height=\"100\">";
container.innerHTML += "<param name=\"number\" value=\"" + num + "\">";
container.innerHTML += "</applet>";
}
</script>
</head>
<body>
Number : <input type="text" id="in" ><br/>
<button id="myBtn" onclick="getVal()">Try it</button><br/>
<div id="applet-container" />
</body>
Sending POST from Java
As I said in my comment, this is a little more complicated. You'd have to POST (you could also use GET) your values to a hosted file (can be any server side scripting technology). The following demonstrates this, code taken from here.
URL url;
URLConnection urlConnection;
DataOutputStream outStream;
DataInputStream inStream;
// Build request body
String body = "key=value";
// Create connection
url = new URL("http://myhostedurl.com/receiving-page.php");
urlConnection = url.openConnection();
((HttpURLConnection)urlConnection).setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", ""+ body.length());
// Create I/O streams
outStream = new DataOutputStream(urlConnection.getOutputStream());
inStream = new DataInputStream(urlConnection.getInputStream());
// Send request
outStream.writeBytes(body);
outStream.flush();
outStream.close();
// Close I/O streams
inStream.close();
outStream.close();

Source from this article
For example:
This is your applet codes:
import java.applet.*;
import java.awt.*;
public class DrawStringApplet extends Applet {
private String defaultMessage = "Hello!";
public void paint(Graphics g) {
String inputFromPage = this.getParameter("Message");
if (inputFromPage == null) inputFromPage = defaultMessage;
g.drawString(inputFromPage, 50, 25);
}
}
Then in HTML:
<HTML>
<HEAD>
<TITLE> Draw String </TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="DrawStringApplet" width="300" height="50">
<PARAM name="Message" value="Howdy, there!">
This page will be very boring if your
browser doesn't understand Java.
</APPLET>
</BODY>
</HTML>
Notice: DrawStringApplet is you applet name; Message is a parameter sent to applet; Applet will then display: Howdy, there! as a result.

Related

How to Pass data from C# server side to htm through webBrowser control?

I am facing a problem passing string to HTML page through javascript.
I have a window form,
A HTML file, where I have my Javascript and HTML code.
In the function in C# page, I have a string that I need to send to the HTML page through javascript. But I can not pass it. Please advise me.
Thanks
My C# method code below
private void Form1_Load(object sender, EventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("ProjectName.Maps.html"));
webBrowser1.DocumentText = reader.ReadToEnd();
***//pass getDefaultMap() value (str) to the javascript in Maps.html page.***
}
private string getDefaultMap()
{
string str;
str = (#"Exec SP_Map_Display #Opt=1");
return str ;
}
My HTML page is below
<body>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
***// Get the data from C# code str***
}
</script>
<input type="button" name="btnSubmit" value="Submit" />
<div id="dvMap">
</div>
</body>
Assuming this is WinForms since there's a WebBrowser control, to call C# code from the HTML page JavaScript can be accomplished with this minimum example:
Simple HTML page added to the root of the project and Properties was setup to Copy to Output Directory: Copy if newer this will ensure there's a simple page for testing:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>WebForms WebBrowser Control Client</title>
</head>
<body>
<input type="button" onclick="getLocations()" value="Call C#" />
<script type="text/javascript">
function getLocations() {
var locations = window.external.SendLocations();
alert(locations);
}
</script>
</body>
</html>
The JS function getLocations will call C# method SendLocations, the important parts are the Form1 class annotations and setting webBrowser1.ObjectForScripting = this :
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;
var path = Path.GetFullPath("Client.html");
var uri = new Uri(path);
webBrowser1.Navigate(uri);
}
public string SendLocations()
{
return "SF, LA, NY";
}
}
Clicking the HTML button Call C# will show a popup with the return value from C# method

Loading .txt file into textarea Javascript?

I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txt and the text file doesn't load into textarea.
<html>
<head>
<title>textbox</title>
<script type="text/javascript">
function readBOX() {
var txtinput = document.getElementById('txtinput').value;
document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
}
</script>
</head>
<body>
<p> Type</p>
<input type="text" id="txtinput" />
<input id="open" type="button" value="READ" onClick="readBOX()" />
<form>
<textarea name="text" rows="20" cols="70">loaded text here</textarea>
</form>
</body>
</html>
You have to use something like its posted in this Answer
jQuery
$(document).ready(function() {
$("#open").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$("#text").text(data);
}
});
});
});
Read more on the jQuery Documentation of .ajax()
Non jQuery
I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
But this can be read on the SO-Answer here or the complete and understandable documentation on Wikipedia
Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP") object
Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.
<!DOCTYPE HTML>
<html>
<head>
<title>textbox</title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>
Process.php
<textarea name="text" rows="20" cols="70">
<?php $name = $_POST["name"]; echo file_get_contents("$name");?>
</textarea>
This is how I load text into a textarea
Main.css
.textbox{
font-size: 12px;
float : left;
height : 197px;
width : 650px; }
Default.html
<!DOCTYPE html>
<html>
<head>
<!-- Charactor set allowed to use -->
<meta charset="utf-8"/>
<title>Text from .txt file to TextArea</title>
<!-- External stylesheet -->
<link rel="stylesheet" href="main.css" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<textarea class="textbox" id="Brief" readonly></textarea>
<script> $( "#Brief" ).load( "text.txt" ); </script>
</body>
</html>
google textarea to find format of text area
One of the easiest way is to request the server to return the pre-filled textarea
(Here's an example using PHP):
<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>
Note: Something similar can be done with any server-side scripting language.
In the meantime, if you need to load it dynamically, your best bet is using an AJAX approach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequest first.
Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):
Pure JS:
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
}
function readBOX() {
function reqListener () {
document.forms[0].text.value = this.responseText;
}
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", filePath, true);
oReq.send();
}
But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:
jQuery:
function readBOX() {
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
$.ajax({
url: filePath
}).done(function(data){
document.forms[0].text.value = data;
});
}
Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.
Hope this helps :)
window.addEventListener('DOMContentLoaded', (e) => {
let input = document.getElementById('input');
// load default.txt into input box
try {
let fileToLoad = './default.txt';
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', fileToLoad, false);
xmlhttp.send();
input.innerHTML = xmlhttp.responseText;
} catch(DOMException) {
input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
}
});

why call flash function from javascript work but FileReference don't work in flash?

I need call flash function from javascript. I use flash.external and addCallback to do this. all things work well but when I use FileReference in my flash, function did not open my browser ...
please see below describtion:
I call my function in javascript with this code:
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
you can see all my HTML as below:
<html>
<head>
<title>Upload test</title>
</head>
<script>
function hello (size) {
alert ("size hast: " + size);
}
function sendToFlash(val){
var flash = getFlashObject();
flash.new_browser(val);
}
var flash_ID = "Movie2";
var flash_Obj = null;
function getFlashObject(){
if (flash_Obj == null){
var flashObj;
if (navigator.appName.indexOf( "Microsoft" ) != -1){
flashObj = window[flash_ID];
}
else{
flashObj = window.document[flash_ID];
}
flash_Obj = flashObj;
}
return flash_Obj;
}
</script>
<body>
<center>
<embed width="560" height="410" type="application/x-shockwave-flash"
flashvars="sampleVars=loading vars from HTML"
salign="" allowscriptaccess="sameDomain" allowfullscreen="false" menu="true" name="Movie2"
bgcolor="#ffffff" devicefont="false" wmode="window" scale="showall" loop="true" play="true"
pluginspage="http://www.adobe.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"
quality="high" src="Movie2.swf">
</center>
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
</body>
</html>
when I click Browse in html page, javascript call sendToFlash function and SendToFlash function send my string (Hello World! from HTML) to flash.
in flash I get this string with below code:
resultsTxtField.text = "";
uploadButton.onPress = function () {
return browse_file("Hello World! from Flash");
}
import flash.external.*;
ExternalInterface.addCallback("new_browser", this, browse_file);
function browse_file (my_test_val) {
_root.resultsTxtField.text = "val: " + my_test_val;
import flash.net.FileReference;
var fileTypes:Array = new Array();
var imageTypes:Object = new Object();
imageTypes.description = "Images (*.jpg, *.jpeg, *.gif, *.png)";
imageTypes.extension = "*.jpg; *.jpeg; *.gif; *.png";
fileTypes.push(imageTypes);
var fileListener:Object = new Object();
var btnListener:Object = new Object();
var fileRef:FileReference = new FileReference();
fileRef.addListener(fileListener);
fileRef.browse(fileTypes);
fileListener.onCancel = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Upload Cancelled\n";
}
fileListener.onSelect = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Selected: " + file.name + " file size: "+ file.size + " file type: " + file.type;
getURL("javascript:hello("+file.size+");");
}
}
I have only one Scene and this code is on root of this Scene. and I have one movie clip named uploadButton and has only a rectangle that work as button in this sample.
when you click on rectangle browse_file("Hello World! from Flash"); called and a browser open that you can select a photo to upload.
when you click on browse in html same process must do but as you see variable send to function but browser to select a photo did not open any more.
I try several ways. for example I set new function to open only picture browser or set new Scene or use gotoAndPlay and more but there is another problem.
you can download my source from below link:
http://www.4shared.com/zip/YTB8uJKE/flash_uploader.html
note that javascript onclick="sendToFlash('Hello World! from HTML');" don't work in direct opening. you must open it in localhost.
I'll be so so happy for any clue.
thanks so much
Reza Amya
You can't programmatically call browse(), it has to be from a mouse click inside Flash: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#browse()
In Flash Player 10 and Flash Player 9 Update 5, you can only call
this method successfully in response to a user event (for example, in
an event handler for a mouse click or keypress event). Otherwise,
calling this method results in Flash Player throwing an Error
exception.
after a day reading I know that it is impossible for security reasons.
then you can't open file reference with addCallback javascript code any way. for more information read fileReference browse from js, simulate keypress in flash workaround
Thanks again
Reza Amya

How can we use addCallback function in flex

How can i call the flex frunction from the java script?
i am using below code which is define in below links
ExternalInterface.addCallback( "javascriptfunction", flexfunction);
http://www.switchonthecode.com/tutorials/flex-javascript-basics-using-externalinterface
http://circlecube.com/2010/12/actionscript-as3-javascript-call-flash-to-and-from-javascript/
You should give more context for your problem. From what I read on the tutorials, it is possible that you have omitted to add security access to your code. More precisely look here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html#addCallback%28%29 , especially here:
SecurityError — The containing environment belongs to a security sandbox to which the calling code does not have access. To fix this problem, follow these steps:
In the object tag for the SWF file in the containing HTML page, set the following parameter:
param name="allowScriptAccess" value="always"
In the SWF file, add the following ActionScript:
flash.system.Security.allowDomain(sourceDomain)
Hope it helps.
In flex 4.5
Add a addcallback first, like this in your mxml
public function initApp():void {
ExternalInterface.addCallback("myFlexFunction",myFunc);
}
myFlexFunction can now be accessed from your javascript.
Make your index.template.html looks like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>addCallback() Wrapper</title>
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
var swfVersionStr = "0";
var xiSwfUrlStr = "";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "sameDomain";
var attributes = {};
attributes.id = "AddCallbackExample";
attributes.name = "AddCallbackExample";
attributes.align = "middle";
swfobject.embedSWF(
"AddCallbackExample.swf", "flashContent",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
</script>
</head>
<SCRIPT LANGUAGE="JavaScript">
function callApp() {
window.document.title = document.getElementById("newTitle").value;
var AddCallbackExample = document.getElementById("AddCallbackExample");
AddCallbackExample.myFlexFunction(window.document.title);
}
</SCRIPT>
<body>
<form id="f1">
Enter a new title: <input type="text" size="30" id="newTitle" onchange="callApp()">
</form>
<div id="flashContent"/>
</body>
</html>
and your flex application like this
<?xml version="1.0"?>
<!-- wrapper/AddCallbackExample.mxml -->
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:s="library://ns.adobe.com/flex/spark" creationComplete="initApp()">
<fx:Script>
import flash.external.*;
public function initApp():void {
ExternalInterface.addCallback("myFlexFunction",myFunc);
}
public function myFunc(s:String):void {
l1.text = s;
}
</fx:Script>
<s:Label id="l1"/>
</s:Application>
Hope this helps

Display HTML and XML content on the same HTML page

I have a HTML page in which I have a button; pressing that button a javascript function is called - here results a String which is the representation of an xml. I want to represent this xml on the same page with the button, similar with what is in the picture below:!
Here is the simplified code I've tried but did not worked (see under the code the result of it - nothing displayed):
<html>
<head>
<script type="text/javascript">
function xml_test()
{
var xmlString = "<note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var my_div = document.getElementById("labelId");
alert(xmlString)
my_div.innerHTML += xmlString;
}
</script>
</head>
<body>
<input type="button" value="TEST" onclick="xml_test()"/>
<br><br>
<label id="labelId">XML: </label>
</body>
</html>
I've tried with an iframe also, but I do not have an file for the src attribute.
What I've tried is:
<html>
<head>
<script type="text/javascript">
function populateIframe() {
var xml = "<?xml version='1.0' encoding='UTF8' standalone='yes'?><note><name>Kundan Kumar Sinha</name><place>Bangalore</place><state>Karnataka</state></note>";
var iframe = document.getElementById('myIframe');
var idoc= iframe.contentDocument || iframe.contentWindow.document; // IE compat
idoc.open("text/xml"); // I know idoc.open(); exists but about idoc.open("text/xml"); I'm not sure if exists;
idoc.write('<textarea name="xml" rows="5" cols="60"></textarea>');
//idoc.write(xml); // doesn't work
idoc.getElementsByTagName('textarea')[0].value= xml;
idoc.close();
}
</script>
</head>
<body onload="populateIframe();">
<iframe id="myIframe" width="900" height="400"></iframe>
</body>
</html>
and the result is:
I've already looked over How to display XML in a HTML page as a collapsible and expandable tree using Javascript?
I took some ideas from here
Thank you for helping me!
Just Create am HttpHandler, and open it in a Iframe:
public class Handler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
XmlSerializer serializer = new XmlSerializer(typeof(Note));
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream, Encoding.Unicode);
serializer.Serialize(writer, new Note() { Name = "Kundan Sinha", Place = "Bangalore", State = "Karnataka" });
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding();
stream.Close();
writer.Close();
context.Response.ContentType = "text/xml;charset=utf-8";
context.Response.Write(utf.GetString(arr).Trim());
context.Response.Flush();
}
#endregion
}
public class Note
{
public string Name { get; set; }
public string Place { get; set; }
public string State { get; set; }
}
You can pass your received xml string to this where I am doing
context.Response.Write('Pass you XML data here');
You must use your favorite JavaScript library with a tree widget to display that XML in tree form.
Note that the "tree-like" view you see is actually IE's default view for XML files. Other browsers will have different views for XML files, and some do not even let you view XML files without a plug-in.
You should not depend on browser-specific functionality if viewing the XML in tree form is important to your page's functionality.
If you, however, just want to press a button and then the whole page gets turned into an XML, then by all means just redirect to that XML URI on button press. IE will show that XML file in tree form, while other browsers may either ask you to download the file, or display the XML file in whatever format that is determined by their plugin's.
I set the xml data in the src attribute:
iframeElement.setAttribute('src', 'data:text/xml,<test>data</test>');

Categories

Resources