How to access to a java variable in javascript function - javascript

I have a java file called myJavaFile.java. Inside this java file, I have the following java code:
private void addUploadscript() {
//my java variable
String fn = session.getUser();
html.addElement("<script language=\"JavaScript\" type=\"text/javascript\">");
html.addElement("function ajax_post(){");
html.addElement("var hr = new XMLHttpRequest();");
html.addElement("var url = \"http://localhost:8080/bunk/inf?cmd=Dialer.opts#\";");
html.addElement("var vars = \"firstname=\"+fn;");
html.addElement("\talert(vars)");
html.addElement("hr.open(\"POST\",url,true);");
html.addElement("hr.setRequestHeader(\"Content-type\",\"application/x-www-form-urlencoded\");");
html.addElement("hr.onreadystatechange = function() {if (hr.readyState == 4 && hr.status == 200) {var return_data = \"my server is reached\";document.getElementById(status).innerHTML = return_data;} } ");
html.addElement("hr.send(vars);");
html.addElement("document.getElementById(status).innerHTML = \"processing....\";");
html.addElement("}");
html.addElement("</SCRIPT>");
}
I already tried to find my response by reading the other topics but I still can not resolve my problem.
I actually tried to do it step by step and display my variables to make sure that I wrote everything fine.
Thank you very much for your help!

I believe you want to output fn directly, something like
html.addElement("var vars = \"firstname=" + fn + "\";");
Javascript allows you to use ' or " for String(s), and you could also use String.format(String, Object...). Like,
html.addElement(String.format("var vars = 'firstname=%s';", fn));

You should change this part of your code:
html.addElement("var vars = \"firstname=\"+fn;");
For this:
html.addElement("var vars = \"firstname=\"" + fn + "\";");

Just use single qoute ' instead of \" in all your code that will make it more cleanest, and replace this part :
html.addElement("var vars = \"firstname=\"+fn;")
By :
html.addElement("var vars = 'firstname='+fn;")
Hope this helps.

Related

inDesign scripting: Include remote .js-file in script-file (and use it's variables)

I'm trying to access a remote .jsfile within an inDesign script to use it's variables. I found functions for including js-files locally but haven't found a good way to include.
http://remote-site.com/test.js:
var testVar = "it works!";
myscript.js, including locally (working):
app.doScript(new File("/Users/Popmouth/test.js"));
alert(testVar);
myscript.js, including locally including remotely (not working):
app.doScript(new File("http://remote-site.com/test.js"));
alert(testVar);
I also found this snippet, this alert works (alerts the content of the file, i.e. "var testVar = "it works!;") but I don't know how to use the vars in my alert function below:
var HTTPFile = function (url,port) {
if (arguments.length == 1) {
url = arguments[0];
port = 80;
};
this.url = url;
this.port = port;
this.httpPrefix = this.url.match(/http:\/\//);
this.domain = this.httpPrefix == null ? this.url.split("/")[0]+":"+this.port :this.url.split("/")[2]+":"+this.port;
this.call = "GET "+ (this.httpPrefix == null ? "http://"+this.url : this.url)+" HTTP/1.0\r\nHost:" +(this.httpPrefix == null ? this.url.split("/")[0] :this.url.split("/")[2])+"\r\nConnection: close\r\n\r\n";
this.reply = new String();
this.conn = new Socket();
this.conn.encoding = "binary";
HTTPFile.prototype.getFile = function(f) {
var typeMatch = this.url.match(/(\.)(\w{3,4}\b)/g);
if (this.conn.open(this.domain,"binary")) {
this.conn.write(this.call);
this.reply = this.conn.read(9999999999);
this.conn.close();
} else {
this.reply = "";
}
return this.reply.substr(this.reply.indexOf("\r\n\r\n")+4);;
};
}
var remoteFile = new HTTPFile("http://remote-site.com/test.js");
alert(.getFile());
This function
Ok, so I went to adobe-forums and got the following string which replaces app.doScript(new File("/Users/Popmouth/test.js"));:
var remoteCode = 'http://remote-site.com/test.js'; //location of your remote file
var script = app.doScript("do shell script \"curl 'remoteCode'\"".replace("remoteCode", remoteCode), ScriptLanguage.APPLESCRIPT_LANGUAGE);
// Set script args
app.scriptArgs.setValue("scriptArg1", "Hello");
// Set environmental vars
$.setenv("envVar1", "World");
// Run the "remote" script
app.doScript(script, ScriptLanguage.JAVASCRIPT);

embed JS code in a batch file

i have a batch file preparing word files by renaming and relocating them.
so that i make pdf for this files using a javascript code i ve found in this website. i call it as follows;
for %%g in ("test\*.doc") do (cscript.exe //nologo "SAVEASPDF.js" "%%~fg")
this JavaScript code is in another file as saveaspdf.js to make PDF.
can i embed a JS code inside the batch file (e.g. as a :FUNCTION) to keep all the code in a single file only?
here is the JS i m trying to embed, i found it here in this website.
var fso = new ActiveXObject("Scripting.FileSystemObject");
var docPath = WScript.Arguments(0);
docPath = fso.GetAbsolutePathName(docPath);
var pdfPath = docPath.replace(/\.doc[^.]*$/, ".pdf");
var objWord = null;
try
{
WScript.Echo("Saving '" + docPath + "' as '" + pdfPath + "'...");
objWord = new ActiveXObject("Word.Application");
objWord.Visible = false;
var objDoc = objWord.Documents.Open(docPath);
var wdFormatPdf = 17;
objDoc.SaveAs(pdfPath, wdFormatPdf);
objDoc.Close();
WScript.Echo("Done.");
}
finally
{
if (objWord != null)
{
objWord.Quit();
}
}
There are many methods posted for embedding and executing JScript within a batch script. Here are a few:
https://stackoverflow.com/a/15169687/1012053
This is my favorite, and the one I will use below
https://stackoverflow.com/a/4999378/1012053
I don't like this method because it defines an extra (unwanted) environment variable.
https://stackoverflow.com/a/15176096/1012053 (before the EDIT)
Another excellent choice.
https://stackoverflow.com/a/9074483/1012053 (The final UPDATE 2014-04-27 at the bottom)
This WSF technique is not quite as convenient, but it is powerful in that you can embed and execute any number of independent JScript and/or VBS jobs within a single batch script.
So here is how you could use option 1. to combine the two scripts into a single file:
#if (#X)==(#Y) #end /* Harmless hybrid line that begins a JScript comment
:: ******* Begin batch code *********
#echo off
for %%g in ("test\*.doc") do cscript //E:JScript //nologo "%~f0" "%%~fg"
exit /b
********* Begin JScript code **********/
var fso = new ActiveXObject("Scripting.FileSystemObject");
var docPath = WScript.Arguments(0);
docPath = fso.GetAbsolutePathName(docPath);
var pdfPath = docPath.replace(/\.doc[^.]*$/, ".pdf");
var objWord = null;
try
{
WScript.Echo("Saving '" + docPath + "' as '" + pdfPath + "'...");
objWord = new ActiveXObject("Word.Application");
objWord.Visible = false;
var objDoc = objWord.Documents.Open(docPath);
var wdFormatPdf = 17;
objDoc.SaveAs(pdfPath, wdFormatPdf);
objDoc.Close();
WScript.Echo("Done.");
}
finally
{
if (objWord != null)
{
objWord.Quit();
}
}
Try this:
ECHO 'YOUR_JS_CODE' | node
http://www.robvanderwoude.com/redirection.php
If you look at the documentation for cscript.exe it seems that it wants to read the script from a file so I believe you are out of luck here.
Running it via nodejs as lleaff suggested might have worked if your script was compatible with nodejs but since you are using ActiveXObject to automate Word it wouldn't execute.

Reading file dynamically with javascript

I'm trying to post values from a file to a textfield on a website. These values will be updated every 5 seconds. I am able to read the values using xmlHTTPrequest, however, when I try to use setInterval to run the function again, the values don't change. It detects if the file is no longer there, but as I put it back and change values, they are the same as before. This is my code:
setInterval(getrecent, 5000);
function getrecent () {
sourcestr = "../userdata/" + sessionStorage.getItem("DoB");
var x = new XMLHttpRequest();
x.open("GET", sourcestr + "/recentdata.txt", false);
x.send();
if (x.status == 404) {
document.getElementById("babypic").src = "../../Notrunning.png";
}
else {
var myTextfile = x.responseText;
// alert(myTextfile);
document.getElementById("babypic").src = sourcestr + "/picture.jpeg" + '?rand=' + Math.random();
var split = myTextFile.split(" ");
document.getElementById("pulse").value = split[0];
document.getElementById("resp").value = split[1];
}
}
I found the error but I'm not sure what to do with it. "Uncaught referenceerror, myTextFile not defined" on row 117 which is "var split = myTextFile.split(" ");
Solved: Added "meta http-equiv="cache-control" content="no-cache" " to the head to avoid caching and corrected spelling of myTextFile. Website works just fine now.
You have written the variable myTextfile in two different casing: myTextFile and myTextfile are not identical variables.
Please correct the casing and think about using an IDE that can point out such errors, it will make your life a lot easier!

How do you get the current sessid from web address and use it in javascript?

Sorry if this is a noob question, network admin unknowingly turned into web developer :) I am trying to understand how to get the current sessid and put it into the javascript where sessid= (current sessid), its on the web address and is generated when you visit the search page. ex: http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=
<script language="JavaScript">
var url= "http://www.southerntiredirect.com/online/system/ajax_search_manufacturer?sessid=????????";
</script><script type="text/javascript" src="http://www.southerntiredirect.com/online/templatemedia/all_lang/manufacturer.js"></script><input type="hidden" name="sessid" value="sessid??????">
Use my handy-dandy library URLTools!
Library
//URLTools- a tiny js library for accessing parts of the url
function urlAnalyze(url) {
if (url == undefined) {var url = document.location.toString();}
url = url.replace(/\%20/g," ");
//seperates the parts of the url
var parts = url.split("?");
//splits into sperate key=values
if (parts[1] == undefined) {return 1;}
var keyValues = parts[1].split("&");
var key = function () {}
keyValues.forEach(function (keyValue) {
var keyAndValue = keyValue.split("=");
key[keyAndValue[0]] = keyAndValue[1];
});
return key;
}
Then, just call URLAnalyze and get the sessid key.
Usage
var urlKeys = urlAnalyze(),
sessid = urlKeys["sessid"];
here is a great function that grabs whatever you want and returns the key, value for it.
The main portion of this function gets the url using window.location.href and then performs a regular expression on it to find botht he key and the value.
I DO NOT TAKE CREDIT FOR THIS CODE.
Please go the link to see the full example
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(
/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
You could use a simple regexp:
var url = "http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=";
var match = url.match(/sessid=([^&]+)/);
if (match === null) {
throw new Error("now what? D:");
}
var sessid = match[1];
The regexp in English: look for "sessid=" then capture anything that isn't an &

How do I pass along variables with XMLHTTPRequest

How do I send variables to the server with XMLHTTPRequest? Would I just add them to the end of the URL of the GET request, like ?variable1=?variable2=, etc?
So more or less:
XMLHttpRequest("GET", "blahblah.psp?variable1=?" + var1 + "?variable2=" + var2, true)
If you want to pass variables to the server using GET that would be the way yes. Remember to escape (urlencode) them properly!
It is also possible to use POST, if you dont want your variables to be visible.
A complete sample would be:
var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
To test this, (using PHP) you could var_dump $_GET to see what you retrieve.
Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.
You could write a simple utility function that handles building the query formatting for you.
function formatParams( params ){
return "?" + Object
.keys(params)
.map(function(key){
return key+"="+encodeURIComponent(params[key])
})
.join("&")
}
And you would use it this way to build a request.
var endpoint = "https://api.example.com/endpoint"
var params = {
a: 1,
b: 2,
c: 3
}
var url = endpoint + formatParams(params)
//=> "https://api.example.com/endpoint?a=1&b=2&c=3"
There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give http://api.jquery.com/jquery.param/ a try.
It is similar to the above example function, but handles recursively serializing nested objects and arrays.
If you're allergic to string concatenation and don't need IE compatibility, you can use URL and URLSearchParams:
const target = new URL('https://example.com/endpoint');
const params = new URLSearchParams();
params.set('var1', 'foo');
params.set('var2', 'bar');
target.search = params.toString();
console.log(target);
Or to convert an entire object's worth of parameters:
const paramsObject = {
var1: 'foo',
var2: 'bar'
};
const target = new URL('https://example.com/endpoint');
target.search = new URLSearchParams(paramsObject).toString();
console.log(target);
The correct format for passing variables in a GET request is
?variable1=value1&variable2=value2&variable3=value3...
^ ---notice &--- ^
But essentially, you have the right idea.
Following is correct way:
xmlhttp.open("GET","getuser.php?fname="+abc ,true);
Yes that's the correct method to do it with a GET request.
However, please remember that multiple query string parameters should be separated with &
eg. ?variable1=value1&variable2=value2
How about?
function callHttpService(url, params){
// Assume params contains key/value request params
let queryStrings = '';
for(let key in params){
queryStrings += `${key}=${params[key]}&`
}
const fullUrl = `${url}?queryStrings`
//make http request with fullUrl
}

Categories

Resources